I know function call back is embedding another function pointer in the call of another function like this:
Function Declaration:
function_call_back(int x, int y, void (*functonPtr)(int x, char y , struct newStruct* sptr))
void func(int x , char y , struct newStruct* sptr1)
{
//perform Algorithm 1 on x,y ,sptr1
}
void func2(int x , char y , struct newStruct* sptr2)
{
//perform Algorithm 1 on x,y ,sptr2
}
void func3(int x , char y , struct newStruct* sptr3)
{
//perform Algorithm 1 on x,y ,sptr3
}
void func4(int x , char y , struct newStruct* sptr4)
{
//perform Algorithm 1 on x,y ,sptr4
}
main()
{
// function calling
function_call_back(23, 2256, func1);
}
Here the third argument is func, as function name is equivalent to function pointer
I agree that the func here can be altered with different variation of similar function signature by adding this line in main above before call to function_call_back:
typedef void (*fptr)(int int x , char y , struct newStruct* ptr);
fptr f1 = func2; // or func3, or func4
function_call_back(23, 2256, f1);
The third argument is func, as function name is but I was wondering this can be achieved in the below way also, by simply adding the function-calling code in the call to function_call_back:
function_call_back(23, 2256, functionCallingcode); //third argument is func
The new declaration of function_call_back is:
function_call_back(int x, int y, int functionCallingCode)
And its new definition is:
void function_call_back(int x, int y, int functionCallingCode)
{
switch(functionCallingCode)
case 1:
func1(1,"g",sptr1);
break;
case 2:
func2(1,"c",sptr2);
break
case 3:
func3(1,"d",sptr3);
break;
case 4 :
func4(1,"s",sptr4);
break ;
default :
printf("Wrong Function calling code");
}
}
Then why to use function pointer?
With the switch statement, you can call every function that you choose to code into your callback function. You are guaranteed that only one of your known collection of functions can be called.
With the function pointer, you can call any function that you may define at a later and completely unrelated point in your development. You’re free to define and use any callback function with a matching signature.
In other words, the switch allows you to branch among a bounded set of choices, while the function pointer gives you unbounded flexibility. Usually there’s little reason to prefer anything else over the function pointer.