main() function calls itself in C++, what will happen? [duplicate]

不羁岁月 提交于 2019-12-13 01:12:18

问题


#include <iostream>

int main()
{
    main();
    std::cout<<"Hello World! "<<std::endl;
    return 0;
}

This is the code, How does it behave? Why?


回答1:


That's undefined behaviour. You cannot call main() from within a C++ program (section 3.6.1.3 of the standard).

Therefore anything can happen. And there's no point in asking why.




回答2:


main() function call itself in C++, what will happen?

Anything can happen, since it's undefined behavior. But as the program is currently standing, some infinite recursion (and eventually a stack overflow) seems reasonable.




回答3:


You should not call main inside main, it is undefined behavior.

§ 5.2.2.9 Function call

Recursive calls are permitted, except to the function named main (3.6.1).

§ 3.6.1

The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is illformed. The name main is not otherwise reserved. [ Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. —end example ]




回答4:


In C++, calling main() from your is not allowed. So it is an error. Even taking its address is error.




回答5:


main() has only one entry point. So, its not allowed to be called again.



来源:https://stackoverflow.com/questions/18460912/main-function-calls-itself-in-c-what-will-happen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!