"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Is Recursively Calling `main()` Allowed in C++?

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

Published on 2024-11-04
Browse:137

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

Calling Main Function Recursively in C

The code snippet provided attempts to call the main() function recursively within itself in C . However, it's important to note that this behavior is not allowed in strict C compliance.

Is Recursively Calling main() Allowed in C ?

According to the C Standard, a function cannot call itself directly, including the main() function. This restriction is intended to prevent infinite recursion and guarantee program termination.

Practical Implementation with g

Despite the language standard, it's possible to call main() recursively in practice using the GNU C compiler (g ). g doesn't strictly enforce the standard in this regard, allowing code with recursive main() calls to compile and execute.

Example Code

The following modified code snippet demonstrates recursive main() calls using g :

#include 
#include 
using namespace std;

int main() {
    int y = rand() % 10; // returns 3, then 6, then 7
    cout 

When compiled and executed, this code will generate the following output:

y = 3
y = 6
y = 7

Assembly Analysis

Examining the assembly generated for this code reveals that g treats recursive main() calls like any other function call:

main:
        ...
        cmpl    $7, -12(%rbp)
        je      .L7
        call    main
        ...
.L7:
        ...
        leave
        ret

Note:

While this behavior is possible with g , it's crucial to note that it's not guaranteed. Other compilers may adhere strictly to the C Standard, resulting in compilation errors or unexpected behavior. Therefore, using recursive main() calls is not a recommended practice.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3