考虑这段代码具有 3 种不同的函数调用语义:
void f(void){
puts("OK");
}
int main(void){
f();
(*f)();
(&f)();
return 0;
}
首先是调用f的标准方式,
第二个是取消引用函数指针的语义,
但在第三个例子中,我将 & 运算符应用于函数名称,它似乎工作正常。
第二种和第三种情况会发生什么?
谢谢。
最佳答案
函数调用总是通过函数指针执行。来自 C99 第 6.5.2.2 节:
The expression that denotes the called function shall have type pointer to function.
然而,在几乎所有情况下,函数类型都会退化为函数指针类型。来自 C99 第 6.3.2.1 节:
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".
所以你的三个电话是这样评估的:
(&f)();
(&(*(&f)))();
(&f)();
全部有效。但显然,第一个 (f()
) 是最干净、最容易阅读的。
关于c - 具有不同语义的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11179689/