C++ void return type of main()

后端 未结 8 2399
灰色年华
灰色年华 2020-12-11 01:58

Some C++ compilers allow the main function to have return type void. But doesn\'t the Operating System require int type value returned to specify

相关标签:
8条回答
  • 2020-12-11 02:05

    The C++ standard does not allow main() to have a return type of void. Most compilers will let it pass for historical reasons, though.

    0 讨论(0)
  • 2020-12-11 02:11

    That's why void main() is not allowed by standard C++ - though some compilers (e.g. gcc) does allow it.

    To make it short: always use int main(), never void main().

    0 讨论(0)
  • 2020-12-11 02:14

    main returning void is accepted for backwards compatibility, but it is not legal.

    In this case, the exit code will be 0. You can still change the exit code, using exit function.

    0 讨论(0)
  • 2020-12-11 02:16

    In languages where a void return from main is legal (not C++), the OS usually sees a return value of 0 on normal (non-exceptional) program termination.

    0 讨论(0)
  • 2020-12-11 02:17

    C++ allows main function to have return type void

    No, it doesn't.

    The C++ standard only requires 2 different types of main signatures. Others may be optionally added if the return type is int.

    Implementations of C++ which allow void return types are incorrect in terms of the C++ standard.

    C++03 standard S. 3.6.1-2:

    An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

    int main() { /* ... */ } 
    int main(int argc, char* argv[]) {/* ... */ }
    

    If you want portable C++ code, or to write good C++ examples then you should always use one of the 2 variations above.

    0 讨论(0)
  • 2020-12-11 02:21

    C++ does not allow main to have a void return type. The published C++ standard requires it to be int. Some C++ compilers allow you to use void, but that's not recommended. In general, the OS doesn't care one way or the other. A specific OS might require a program to give a return value, but it doesn't necessarily have to come from main's return value. If the C++ compiler allows void, then it probably provides some other means of specifying the program's exit code.

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