Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-10-31 20:26:29
Original
658 people have browsed it

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();
}
Copy after login

Upon execution:

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

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>
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!