Monday, December 3, 2007

Function pointer in C

#include stdio.h


void func (int);
void one (int, float);
void two (int, float);
void three (int, float);
void four (int, float);
void five (int, float);

int main ()
{
char findex;

/* Function pointer Declaration */
void (*fp) (int); /* single argum,ent */
void (*fptr) (int, float); /* two argument */

/* Function array pointer Declaration */
void (*fparr[]) (int, float) =
{
one, two, three, four, five}; /* initializers */

printf (" Ordinary function calling five(1,3.4)\n");
five (1, 3.4);

printf (" Calling by function pointer fptr(1,3.4); \n");
fptr = five;
fptr (1, 3.4);

printf (" Calling by fun. array ptr (*fparr[findex]) (1, 3.4) \n");
findex = 4; /* To call five(arg1,arg2) fun. index is 4 */
(*fparr[findex]) (1, 3.4); /* passing argument 1, 3.4 */

printf (" Calling func by single argument function pointer \n");
fp = func;
(*fp) (2); /* Mtd 1 */
fp (2); /* Mtd 2 */

exit (EXIT_SUCCESS);
}

void func (int arg)
{
printf ("func arg: %d\n", arg);
}

void one (int arg, float arg2)
{
printf ("Four %f\n", arg2);
printf (" %d\n", arg);
}

/* Similerly define of thwo three...four*/

void five (int arg, float arg2)
{
printf ("Five %f\n", arg2);
printf (" %d\n", arg);
}

No comments: