Home > Backend Development > C++ > Can the main() function call itself in C ?

Can the main() function call itself in C ?

Susan Sarandon
Release: 2024-11-03 00:09:02
Original
964 people have browsed it

Can the main() function call itself in C  ?

Recursion in main() Function: An Unexpected Compiler Behavior

Calls to the main() function are generally not allowed in C . However, in practice, it may be possible on some platforms, particularly on Linux systems with the g compiler. Let's delve into how this behavior is achieved.

In the provided code example:

<code class="cpp">#include <iostream>
#include <cstdlib>

int main() {
    cout << "!!!Hello World!!!" << endl;
    system("pause");
    return main();
}</code>
Copy after login

The call to main() within the main() function allows for an endless loop. However, this is not standard C behavior.

Compiler Magic or Undefined Behavior?

Is it possible to obtain the current running function using a magic variable or macro? No, there is no such provision in the C Standard.

Linux Compiler Exception

Despite the Standard's prohibition, the Linux g compiler compiles code with main() calls within main() without raising errors. This is due to the compiler's lenient interpretation of the C Standard.

Practical Demonstration

Consider the following code:

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

When compiled with g , this code generates assembly code that looks like:

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

In this assembly code, main is called just like any other function. The call to main() in the main() function is translated into a regular function call.

Conclusion

While calling main() from within main() is not allowed by the C Standard, it may be possible to do so on certain platforms with specific compilers that tolerate such behavior. However, it is important to emphasize that this is not standard C and may lead to unexpected results in different environments or versions of compilers.

The above is the detailed content of Can the main() function call itself in C ?. 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