c - 应用于函数的一元 & 运算符的结果

标签 c gcc function-pointers c99 unary-operator

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

据我了解,这表明除非 sizeof 运算符和一元 & 运算符应用于函数;不会发生指针转换的函数。但据我所见,

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

或者,

int (*p)(int) = foo;

两者似乎都有效。这表明 &foofoo 是等价的。那么,如果一元 & 运算符具有如上所示的效果,它会影响到哪里?

最佳答案

你以某种方式理解了它。相反,函数 类型自动衰减为函数指针 类型除非函数标识符在sizeof&

同样,在 sizeof& 函数类型下,不会退化为指针。在所有其他情况下,它会衰减为指针类型。 (这反过来导致将 sizeof 应用于函数是非法的。)

C 中函数类型的行为反射(reflect)了众所周知的数组类型行为:除非您在 sizeof& 下使用它们,否则它们会立即隐式转换为指针类型。

这意味着在您的示例中,表达式 &foofoo 是等价的。在第一种情况下,指针是由 & 的显式应用产生的。在第二种情况下,指针是由隐式的“函数类型衰减”特性产生的。两种情况下指针值相同。

关于c - 应用于函数的一元 & 运算符的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664996/

相关文章:

c - C中的部分线程排序

c - CUDA 上的 BFS 实现问题

c - 访问 int (*foo)[3] 的索引 4 时没有警告

模板内的 C++ 函数指针

c - OpenCV Haar 分类器 XML 生成错误

c - 这个哈希函数是如何工作的?这些数字是随机的吗?

c++ - 将 VS 移植到 linux : no matching function for call to

gcc 和 clang 警告/错误标志

C++0x 模板函数对象推断

c++ - 将函数指针保存在数组 C++ 中