What was Wrong with void main()?

前端 未结 4 780
鱼传尺愫
鱼传尺愫 2021-01-01 16:02

Why has setting the entry point\'s return type to void in C++ always been discouraged, and was later removed by the standard and is prohibited by modern compile

相关标签:
4条回答
  • 2021-01-01 16:42

    You generally want to know the exit status of your program. That's the reason why you have the int main() -- you return your exit status.

    0 讨论(0)
  • 2021-01-01 16:55

    It's wrong because this is not what the C++ Standard specifies as a legal main. Nobody cares about what the other languages specify. For C++ programs, only the C++ Standard is relevant, and it says int.

    0 讨论(0)
  • 2021-01-01 17:00

    C++ has never permitted void main(), though some compilers might permit it either as an extension or just because they don't diagnose it.

    Similarly C has never permitted void main() other than as an extension; the same 1989 standard that introduced the void keyword defined the two standard definitions for main: int main(void) and int main(int argc, char *argv[]).

    Other languages permit it because, well, they're other languages.

    There is no particular advantage in being able to write void main() rather than int main(). You don't even need to explicitly return a value; falling off the end of main is equivalent to return 0; (in C++, and in C starting with C99).

    0 讨论(0)
  • 2021-01-01 17:03

    The C++ standards committee likely chose to require int main() because of the large body of existing code that expected to use a return statement to return a specific exit code to the runtime system. It would be unreasonable to expect all existing code to change to use exit() instead, so int main() was made a requirement in the standard.

    A language such as Java, when it was designed, did not have any body of existing code that it needed to remain compatible with. Therefore, the designers could choose void main() and require the use of System.exit() for non-zero exit codes.

    So, the thing that would be "wrong" with choosing void main() for the C++ standard would be that it would break existing code that expected to use return and an exit code value from main().

    0 讨论(0)
提交回复
热议问题