3

What is the difference between these 2 declaration:

int operate(int (*func)(int, int), int a, int b){
    return (*func)(a, b);
}

and

int operate(int func(int, int), int a, int b){
        return func(a, b);
 }

These two also seems to be equivalent: operate(sum, 1, 1) and operate(&sum, 1, 1)

If I pass function sum as a function of 2 numbers in the place of func, the result are still the same. Why?

David Nehme
  • 21,379
  • 8
  • 78
  • 117
wakandan
  • 1,099
  • 4
  • 19
  • 27

2 Answers2

4

§6.7.5.3/8:

A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.

In other words, the two function declarations are identical.

As far as the function call goes, §6.5.2.2/3:

A postfix expression followed by parentheses () containing a possibly empty, comma-separated list of expressions is a function call. The postfix expression denotes the called function.

Since both func(a, b); and (*func)(a, b) are postfix expressions followed by parentheses, they're both function calls. Since func and (*func) both designate the same function, they both call the same function.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

The two function prototypes are equivalent. From C99, 6.7.5.3:

A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.

The two function calls (operate(sum, 1, 1) and operate(&sum, 1, 1)) are equivalent; a function decays into a function-pointer in most contexts (similar to how an array decays into a pointer to its first element). From C99, 6.3.2.1:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680