Showing posts with label Function Pointer. Show all posts
Showing posts with label Function Pointer. Show all posts

Sunday, August 28, 2011

What is Function Pointer

Function pointer points to the address of a function. It just a pointer or variable.

Uses of function pointer:

1. To replace switch/if else statement
2. Implement callback or late-binding
3. Allocation of  space in memory of a this function is very less the the normal function.
4. etc.
It is only important how you, or better your compiler/processor, interpret the memory a pointer points to.


//define a function pointer and initialize to NULL
        int (*pt2Function)(float, char, char) = NULL;
//define the calling convention
        void __cdecl DoIt(float a, char b, char c); // Borland and Microsoft
        void DoIt(float a, char b, char c) __attribute__((cdecl)); // GNU GCC
//assignment of an address to a function pointer
        pt2Function = DoIt; // short form
        pt2Function = &DoMore; // correct assignment using address operator
//calling a function using a function pointer
        int result1 = pt2Function (12, ’a’, ’b’); // C short way
        int result2 = (*pt2Function) (12, ’a’, ’b’); // C