Home >Backend Development >C++ >Is Recursively Calling `main()` in C Allowed?

Is Recursively Calling `main()` in C Allowed?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 07:03:01644browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn