Printing strings and the passed arguments using function pointer in C programming

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TP)

Other info: none

To do: Printing strings and the passed arguments using function pointer

To show: How to use function pointer in C programming

 

 

/* Pointer to a function */

#include <stdio.h>

 

/* function prototypes */

void funct1(int);

void funct2(int);

 

/* Making FuncType as an alias for the type 'function with one int argument and no return value'.

This means the type of func_ptr() is 'pointer to function with one int argument and no return value'. */

typedef void FuncType(int);

 

/* main() function receive nothing and returning an integer */

int main(void)

{

FuncType *func_ptr;

 

printf("I'm in main()...\n");

/* put the address of funct1 into func_ptr() */

func_ptr = funct1;

 

/* call the function pointed to by func_ptr() with an argument of 100 */

(*func_ptr)(100);

 

/* put the address of funct2 into func_ptr() */

func_ptr = funct2;

 

/* call the function pointed to by func_ptr() with an argument of 200 */

(*func_ptr)(200);

 

return 0;

}

 

/* function definitions */

void funct1 (testarg)

{

printf("I'm in funct1()...\n");

printf("funct1 got an argument of %d\n", testarg);

}

 

void funct2 (testarg)

{

printf("I'm in funct2()...\n");

printf("funct2 got an argument of %d\n", testarg);

return;

}

 

Output example:

 

I'm in main()...

I'm in funct1()...

funct1 got an argument of 100

I'm in funct2()...

funct2 got an argument of 200

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index