Home >Backend Development >C++ >Does `main()` Truly Mark the Absolute Beginning of a C Program?
The Misconception of Main() as the Absolute Start in C
Contrary to popular belief, the C Standard in section $3.6.1/1, by stating that "A program shall contain a global function called main, which is the designated start of the program," does not imply that no code precedes the execution of main(). Instead, it establishes the concept of "start" as a specific point within the program.
To illustrate this distinction, consider the following code snippet:
int square(int i) { return i*i; } int user_main() { for ( int i = 0 ; i < 10 ; ++i ) std::cout << square(i) << endl; return 0; } int main_ret= user_main(); int main() { return main_ret; }
This code initializes the global variable main_ret by executing user_main() before invoking the main() function. Despite this execution order, user_main() is not considered the true "start" of the program as defined by the Standard.
Definition of "Start" in C Standard
The crux of the matter lies in the interpretation of "start." The Standard designates main() as the "designated start" of the program, effectively defining "start" as the point where main() is called. It does not, however, forbid code execution prior to this designation.
Implications for Code Compliance
In light of this interpretation, the given code snippet is fully compliant with the C Standard. Even though user_main() executes before main(), the program's "start" remains at the point where main() is called.
Conclusion
While it may seem intuitive that main() should be the absolute start of a C program, the Standard employs a different definition. It establishes main() as the designated point where the program "starts" for the purposes of its further execution and specification.
The above is the detailed content of Does `main()` Truly Mark the Absolute Beginning of a C Program?. For more information, please follow other related articles on the PHP Chinese website!