Rajesh said:
Dear All,
Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?
The principal advantage of a function pointer is that
it allows you to select the called function at run time
instead of at compile time.
("Huh?")
Example:
int function(void) {...} /* an actual function */
int junction(void) {...} /* another function */
int (*fptr)(void); /* a function pointer */
...
x = function(); /* always calls `function' */
y = junction(); /* always calls `junction' */
z = (*fptr)(); /* calls ... what? */
The final line (which could also be written `z = fptr();',
by the way) calls a function, but just which function it calls
depends on the value stored in `fptr'. If you execute that
line several different times with several different `fptr'
settings, the exact same line of code can call a different
function each time.
It's really not that different from using data pointers:
int x; /* a variable */
int y; /* another */
int *p; /* a pointer */
...
x = 42; /* always stores to `x' */
y = 624; /* always stores to `y' */
*p = 666; /* stores to ... where? */
Depending on the value in `p', the final line might store
to `x' or to `y' or to somewhere else entirely, and the
destination might be different at each execution. You get to
choose the destination at run time instead of fixing it
immutably at compile time -- that's the advantage of a data
pointer, and the advantage of a function pointer is similar.