C/function pointers
Expert: Narendra - 7/11/2006
Questionin an interview i was asked to write a program which receives 3 values and selects a function according to the value received? For eg., funcion A if 1 is received, function B for 2 and function C for 3. I was asked to do this with function pointers.
-------------------------
Followup To
Question -
What are function pointers? Why is it used? how can we use function pointer instead of switch-case?
Answer -
What are function pointers?
Function pointers are basically pointers.
Instead of holding an address of data, it holds the address of a function.
Why is it used?
To indirectly call functions.
Callbacks are implemented using this mechanism.
how can we use function pointer instead of switch-case?
No, they are not a replacement for switch-case.
Answerint fun()
{
}
calling_fn(int ch)
{
// Declare your function pointer here, say *fn.
switch (ch)
{
case 1: fn = A;
break;
case 2: fn = B;
break;
case 3: fn = C;
break;
}
fn();
}