Hi all,
I'm wondering about the point of pointers to functions. When is it used?
I saw the below example. It doesn't make sense to me. I mean we can easily write code that does the same without having to use pointers. Thanks.
Code:
#include <stdio.h>
int addInt(int a, int b); // Adds 2 integers
int add5to4(int (*function_pointer)(int, int));
int main(void)
{
int sum;
int (*function_pointer)(int, int);
function_pointer = &addInt;
sum = (*function_pointer)(2, 3);
printf("Sum: %d\n", sum);
sum = function_pointer(5,6); // Alternative way.
printf("Sum: %d\n", sum);
sum = add5to4(*function_pointer);
printf("Sum: %d\n", sum);
return 0;
}
int addInt(int a, int b)
{
return a + b;
}
int add5to4(int (*function_pointer)(int, int))
{
return (*function_pointer)(5, 4);
}