C++中函数作为变量的语义是什么
What are the semantics of function as variable in C++
像这样将函数声明为变量的语义是什么:
int main() {
int foo();
std::cout << foo; // prints 1
}
编辑:
为什么这不会导致链接器错误?
如果您查看 this attempt to replicate your problem,您会看到来自编译器的警告消息:
main.cpp:5:18: warning: the address of 'int foo()' will never be NULL [-Waddress]
指向函数的指针永远不会是空指针。 但是 因为你只有一个原型,一个声明,而不是任何实际的函数定义,编译器将它评估为 "true"。
用 C++ clang 编译器编译你的程序并看到警告:
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'.
像这样将函数声明为变量的语义是什么:
int main() {
int foo();
std::cout << foo; // prints 1
}
编辑: 为什么这不会导致链接器错误?
如果您查看 this attempt to replicate your problem,您会看到来自编译器的警告消息:
main.cpp:5:18: warning: the address of 'int foo()' will never be NULL [-Waddress]
指向函数的指针永远不会是空指针。 但是 因为你只有一个原型,一个声明,而不是任何实际的函数定义,编译器将它评估为 "true"。
用 C++ clang 编译器编译你的程序并看到警告:
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'.