1

Reading about function pointers, came a question, and I found some answers here at stackoverflow, but I still do not understand.

So, what is the difference between these codes ? What the compiler sees ? Is there a correct way or a good programming practice to do this ?

#include<stdio.h>

int sum(int a, int b);
void handle(int a, int b, int (*func)(int, int));

int main()
{
    handle(1, 2, sum); /*Here the third argument can be sum or &sum*/

    return 0;
}

void handle(int a, int b, int (*func)(int, int))
{
    printf("\nResult: %d.\n\n", func(a, b)); /*Here the second argument can be func(a, b) or (*func)(a, b)*/
}

int sum(int a, int b)
{
    return a + b;
}

I can call handle in two ways:

handle(1, 2, sum);
handle(1, 2, &sum);

And into handle, I can call printf in two ways:

printf("\nResult: %d.\n\n", func(a, b)); 
printf("\nResult: %d.\n\n", (*func)(a, b));

All these ways can be combined, so we have 4 different combined ways.

Thanks !

ViniciusArruda
  • 970
  • 12
  • 27
  • Can you add those answers that you've looked at so far? – Ross Jun 02 '15 at 01:48
  • 1
    [One question that I've looked](http://stackoverflow.com/questions/6893285/why-do-all-these-crazy-function-pointer-definitions-all-work-what-is-really-goi) – ViniciusArruda Jun 02 '15 at 01:53
  • The duplicate is a C++ question, however in this respect the two languages are the same – M.M Jun 02 '15 at 02:12
  • @MattMcNabb: I'm not so sure that this is a real duplicate, because although both these questions overlap significantly, I don't think a good answer to [the other question](https://stackoverflow.com/questions/6893285/why-do-all-these-crazy-function-pointer-definitions-all-work-what-is-really-goi) would necessarily answer the core question here, which as I see it is *"Is there a correct way or a good programming practice to do this ?"* – caf Jun 02 '15 at 02:49
  • Also, as long as we're telling people not to ask "C/C++" questions because they're distinct languages, we shouldn't be pointing questions about C to answers about C++, even if they happen to be applicable in the given case. – caf Jun 02 '15 at 02:51
  • @caf If both languages handle the situation in exactly the same way, I don't think it is necessary to have two parallel threads that will have identical questions and answers but with a slightly different tag. – M.M Jun 02 '15 at 03:56
  • @caf your answer seems sufficient to answer the third of OP's questions – M.M Jun 02 '15 at 03:57

1 Answers1

2

Formally, both are just as correct as each other, and in practice you are likely to see either used.

Personally I would use:

handle(1, 2, sum);

and

printf("\nResult: %d.\n\n", func(a, b));

because I do not think the extraneous operators add any value.

caf
  • 233,326
  • 40
  • 323
  • 462