correct way to assign function pointer

大兔子大兔子 提交于 2019-11-29 01:56:37

foo and &foo values are equivalent in C and have same type.

The & operator here is correct but redundant.

Note that assigning a function pointer to a void * is not valid in C.

void *fp1 = foo;   // invalid
int (*fp2)() = foo;  // valid
int (*fp3)() = &foo; // valid

(These are actually declarations but the constraints of the assignment operator apply.)

Let me explain a bit more.

foo and &foo values are equivalent in C and have same type.

This is not fully correct as pointed out by the comments to the answer by @ouah. Particularly:

  1. sizeof(foo) is invalid, and sizeof(&foo) is the size of a pointer.
  2. &foo is the pointer to foo, while &(&foo) is invalid.

However, they are actually the same in all the other cases, as is mentioned by the standard of C (reference to, e.g., the draft of C11):

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

The sizeof and unary & operators are the only two exceptions when a function designator is not converted to a pointer.

P.S. You can also find why sizeof(foo) and &(&foo) is invalid:

6.5.3.2.1: The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

6.5.3.4.1 The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!