What happens if main() does not return an int value?

前端 未结 8 1642
渐次进展
渐次进展 2020-12-03 03:19

I know that in C compilers the main() function is called by the _start() function which has code something like this:

exit(main());         


        
8条回答
  •  一整个雨季
    2020-12-03 03:46

    The C standard never mentions this _start function; I don't believe C++ does either.

    In C prior to the 1999 ISO standard, if execution reaches the end of main() without executing a return statement, or executes a return statement that doesn't specify a value, then "the termination status returned to the host environment is undefined". In practice, I've seen implementations where such a program returns a status of 1 (failure), or some arbitrary value in memory such as the result of the last function that was called.

    The 1999 ISO C standard changed this: "reaching the } that terminates the main function returns a value of 0". This matches the rule that C++ has had at least since the first ISO C++ standard in 1998.

    (As a matter of style, I prefer to have an explicit return 0; at the end of main, even if it's not strictly required. This is consistent with int functions other than main, and it makes for better portability to pre-C99 C compilers.)

    All this assumes that main is defined with a return type of int. That's the only type that's specifically supported by the C standard (either int main(void) or int main(int argc, char *argv[]) or equivalent), but (hosted) implementations may support other implementation-defined definitions. The C90 standard doesn't explicitly cover this case, but C99 says, "If the return type is not compatible with int, the termination status returned to the host environment is unspecified."

    The C++ standard is a bit different. For hosted implementations, main must be defined to return int. The parameters are implementation-defined, but both the standard forms of C must be supported.

    For a hosted implementation in either C or C++, there is no good reason I know of to define main with a return type other than int. Just use one of the two standard definitions, and the question won't arise.

    For "freestanding implementations", "the name and type of the function called at program startup are implementation-defined". So the entry point might legitimately return void or something else, and it might not even be called main. Note that a "freestanding implementation" is one "in which C program execution may take place without any benefit of an operating system", typically an embedded system.

提交回复
热议问题