函数作为变量的语义是什么 C++.

What are the semantics of function as variable in C++

本文关键字:语义 是什么 C++ 变量 函数      更新时间:2023-10-16

像这样将函数声明为变量的语义是什么:

int main() {
int foo();
std::cout << foo; // prints 1
}

编辑: 为什么这不会导致链接器错误?

如果您查看此复制问题的尝试,您将看到来自编译器的警告消息:

main.cpp:5:18: warning: the address of 'int foo()' will never be NULL [-Waddress]

指向函数的指针永远不能是空指针。但是,由于您所拥有的只是一个原型,一个声明,而不是任何实际的函数定义,因此编译器将其评估为"true"。

在 clang 编译器中编译程序C++并看到警告:

Warning(s):
source_file.cpp:5:12: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
int foo();
^~
source_file.cpp:5:12: note: replace parentheses with an initializer to declare a variable
int foo();
^~
= 0
source_file.cpp:6:18: warning: address of function 'foo' will always evaluate to 'true' [-Wpointer-bool-conversion]
std::cout << foo; // prints 1
~~ ^~~
source_file.cpp:6:18: note: prefix with the address-of operator to silence this warning
std::cout << foo; // prints 1
^
&
2 warnings generated.

为什么输出 1?

因为根据函数的警告地址,"foo"将始终计算为"true"。