سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

In

int (*p)(int) = foo;

the automatic conversion to a function pointer takes place, so that it is equivalent to

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

where the conversion to a function pointer is not automatic but achieved by the & operator.

The implicit pointer to which foo is usually converted has no address that could be taken. And if its address were possible to be taken, it would not be the address of foo.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top