Search code examples
cgccfunction-pointersc99unary-operator

Result of unary & operator applied to a function


C99 6.3.2.1/4

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".

As I understand, this suggests that except when sizeof operator and unary & operator is applied to function; no function to pointer conversion will happen. But from what I've seen,

int (*p)(int) = &foo;

or,

int (*p)(int) = foo;

Both seems to work. This shows that both &foo and foo are equivalent. So, where does unary & operator comes in affect if it has effect as seen above?


Solution

  • You somehow understood it backwards. On the contrary, function type automatically decays to function pointer type unless the function identifier is used under sizeof or &.

    Again, under sizeof and & function type does not decay to pointer. In all other cases it decays to pointer type. (This, in turn, leads to the fact that applying sizeof to functions is illegal.)

    The behavior of function types in C mirrors the well-known behavior of array types: unless you use them under sizeof or &, they are immediately and implicitly converted to pointer types.

    This means in your examples expressions &foo and foo are equivalent. In the first case the pointer is produced by the explicit application of &. In the second case, the pointer is produced by the implicit "function type decay" feature. The pointer value is the same in both cases.