Home >Backend Development >C++ >Is Recursively Calling `main()` in C Allowed?
Can main() Be Called Recursively in C ?
The code snippet below demonstrates the curious behavior of calling main() recursively in C .
<code class="cpp">#include <iostream> #include <cstdlib> int main() { std::cout << "!!!Hello World!!!" << std::endl; system("pause"); return main(); }</code>
The code compiles successfully, and when executed, it displays "Hello World!!!" indefinitely. However, it is important to note that this behavior is not standard-compliant in C . The C Standard explicitly forbids calling main() recursively or taking its address.
In practice, however, some compilers, such as the Linux g compiler, allow main() to be called in main(). This permissiveness is evident in the following code:
<code class="cpp">#include <cstdlib> #include <iostream> using namespace std; int main() { int y = rand() % 10; cout << "y = " << y << endl; return (y == 7) ? 0 : main(); }</code>
When executed, this code generates a series of "y" values (e.g., 3, 6, 7), each from a subsequent call to main().
Analyzing the compiled assembly reveals that main() is called just like any other function:
<code class="assembly">main: ... cmpl , -12(%rbp) je .L7 call main ... .L7: ... leave ret</code>
Despite the Standard's prohibition, g seems to tolerate such calls. However, this behavior is not guaranteed, and programmers should avoid relying on it to ensure portability and compliance with the C Standard.
The above is the detailed content of Is Recursively Calling `main()` in C Allowed?. For more information, please follow other related articles on the PHP Chinese website!