Hemant Bhargava Hemant Bhargava - 2 months ago 19
C Question

How writing function pointers are better than calling them functions?

I had pleasure of working with function pointers lately. I got to know how they work. Classical example of function pointers is :

int add() {
return (100+10);
}
int sub() {
return (100-10);
}

void print(int x, int y, int (*func)()) {
printf("value is : %d", (x+y+(*func)()));
}

int main() {
int x=100, y=200;
print(x,y,add);
print(x,y,sub);
}


Somebody asked me the other day that how is it better than calling(inside main):

print(add(x,y));
print(sub(x,y));


and I struggled to explain that. Is it only about the stack or there is something else lying underneath?

Answer

I don't really understand why the code you show would be a classical example of function pointers. Functions pointers' utility is much more obvious from code like this:

void process(int *p, size_t len, int (*f)(int))
{
  for (size_t i = 0; i < len; ++i)
    p[i] = f(p[i]);
}

Basically, if you accept a pointer to function as a parameter, it allows you to apply a client-provided operation on data of your choice.