Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-11-01 07:03:01
Original
582 people have browsed it

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

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

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

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!

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!