Home  >  Article  >  Backend Development  >  Can g Recursively Call `main()` in C Despite the Standard Forbidding It?

Can g Recursively Call `main()` in C Despite the Standard Forbidding It?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 20:26:29660browse

Can g   Recursively Call `main()` in C   Despite the Standard Forbidding It?

Calling main() recursively in C

The C Standard dictates that calling main() recursively is not allowed. However, g compiler permits this practice, allowing for unusual code such as:

<code class="cpp">#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
 int y = rand() % 10; // returns 3, then 6, then 7
 cout << "y = " << y << endl;
 return (y == 7) ? 0 : main();
}

Upon execution:

> g++ g.cpp; ./a.out
y = 3
y = 6
y = 7</code>

Examining the assembly code reveals that main is invoked similarly to any other function:

<code class="assembly">main:
        ...
        cmpl    , -12(%rbp)
        je      .L7
        call    main
        ...
.L7:
        ...
        leave
        ret</code>

While this behavior is not standardized, g appears to have a relaxed approach to enforcing the standard, as evidenced by its lack of objections. However, it issues a sarcastic warning when using the -pedantic flag:

g.cpp:8: error: ISO C++ forbids taking address of function '::main'

The above is the detailed content of Can g Recursively Call `main()` in C Despite the Standard Forbidding It?. 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