Home >Backend Development >C++ >Can C 's `main()` Function Be Recursive?

Can C 's `main()` Function Be Recursive?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 22:54:14339browse

Can C  's `main()` Function Be Recursive?

Recursivity Restrictions in C 's main() Function

In C , the use of recursion within the main() function has been a subject of debate. Numerous developers have observed that the GNU Compiler Collection (g ) permits recursion in main() despite the alleged prohibition in the C standard.

Standard Restrictions

As per the C standard (3.6.1/3), recursion in main() is explicitly forbidden:

"The function main shall not be used (3.2) within a program."

Definition of "Used"

The standard also defines "used" as an object or non-overloaded function:

"An object or non-overloaded function is used if its name appears in a potentially-evaluated expression."

Therefore, calling main() from within itself constitutes "use" and is hence disallowed according to the standard.

Compiler Behavior

Despite the standard's prohibition, g compiles the following code without error:

int main()
{
    main();
}

This discrepancy arises because g 's default optimization level includes inlining functions smaller than a preconfigured threshold. Since the recursion in this code is a single function call, it likely falls below the threshold and is inlined by g .

Conclusion

While g may permit recursion in main() in some cases, the C standard strictly forbids it. Developers should adhere to the standard's requirements to ensure program correctness and potential pitfalls.

The above is the detailed content of Can C 's `main()` Function Be Recursive?. 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