- Prison Code Breaker Diary -

=> aka: Nhật Kí Code Tù

Categories

My friend asked me for illustrating the idea of function pointer.
Then I wrote this small code for him.


/* HEADER */
#include <stdio.h>
/* DECLARE */
int Calculate( int, int, int (*pFunc)( int, int ) );

int Add( int, int );
int Sub( int, int );
int Mul( int, int );

/* MAIN */
int
main( int argc, char *argv[] )
{
int (*p)(int, int) = NULL;

printf("[ USING REFERENCE ]\n");
printf("Result = %d\n", Calculate( 4, 5, &Add ) );
printf("Result = %d\n", Calculate( 4, 5, &Sub ) );
printf("Result = %d\n", Calculate( 4, 5, &Mul ) );

printf("[ USING POINTER ]\n");
p = &Add;
printf("P Result = %d\n", Calculate( 4, 5, p ) );
p = ⋐
printf("P Result = %d\n", Calculate( 4, 5, p ) );
p = &Mul;
printf("P Result = %d\n", Calculate( 4, 5, p ) );
return 0;
}

/* DEFINITION */
int
Calculate( int a, int b, int (*pFunc)( int, int ) )
{
return pFunc( a, b );
}

int Add( int a, int b )
{
return ( a + b );
}

int Sub( int a, int b )
{
return ( a - b );
}

int Mul( int a, int b )
{
return ( a * b );
}

Have fun!@

0 comments

Post a Comment