我正在阅读C++常见问题,我注意到了一句话.
main()不能内联.
为什么是这样?
任何人都可以告诉下面的代码有什么问题吗?
int main () {
return main();
}
Run Code Online (Sandbox Code Playgroud)
我测试过,它编译正确.它一直在运行.现场背后的诀窍呢?
请使用以下代码:
int main()
{
decltype(main()) x = 0;
return x;
}
Run Code Online (Sandbox Code Playgroud)
gcc抱怨:
main.cpp: In function 'int main()':
main.cpp:8:19: warning: ISO C++ forbids taking address of function '::main' [-Wpedantic]
decltype(main()) x = 0;
^
main.cpp:8:19: warning: ISO C++ forbids taking address of function '::main' [-Wpedantic]
Run Code Online (Sandbox Code Playgroud)
但没有铿锵 那么怎么decltype(main())会引发这个错误呢?怎么decltype拿主要的地址?
我在C++ Primer中读到了main不允许递归调用的问题,并且在SO的一些相关问题中确实证实它是非法的.
但为什么这是非法的?只要你避免堆栈溢出,调用main内部的问题是什么?
C++ 标准文档中明确指出程序不能调用 main。但我编写了一个调用 main 的程序并且运行得很好,这是为什么呢?代码:
#include<iostream>
static int counter = 0;
int main(){
counter++;
std::cout << counter << " It works" << std::endl;
while(counter < 10){
main();
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
它打印到控制台“It Works” 10 次。根据标准文档,这不应该起作用,但它确实有效。这是怎么回事?