Home >Backend Development >C++ >Is Recursion into Main() Legally Allowed in C ?

Is Recursion into Main() Legally Allowed in C ?

DDD
DDDOriginal
2024-11-12 16:41:02929browse

Is Recursion into Main() Legally Allowed in C  ?

Exploring the Legality of Recursion into Main() in C

A recurring debate among programmers is the legality of recursion into main() in C . While some sources suggest it is forbidden, others demonstrate the seemingly contradictory behavior of compilers accepting such code.

The C Standard's Perspective

According to the C standard in 3.6.1/3, recursion into main() is explicitly prohibited: "The function main shall not be used within a program."

Understanding "Used" in the Context of the Standard

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

In the case of the example code presented:

int main()
{
    main();
}

The call to main() appears within the body of main(), which is a potentially-evaluated expression. Therefore, by the standard's definition, main() is used within the program, rendering it illegal.

Compiler Behavior and Potential Exceptions

Despite the standard's prohibition, compilers like g may compile such code without error. This behavior is generally not recommended and should not be relied upon. Compilers may handle such situations in non-standard or implementation-specific ways.

Avoiding Recursion into Main()

To ensure compliance with the C standard and avoid potential issues, it is strongly advised to avoid recursion into main(). Instead, consider using alternative design patterns or programming techniques to achieve the desired functionality without violating the language's rules.

The above is the detailed content of Is Recursion into Main() Legally Allowed in C ?. 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