Why does int main() {} compile?

后端 未结 4 615
时光取名叫无心
时光取名叫无心 2020-12-02 22:32

(I\'m using Visual C++ 2008) I\'ve always heard that main() is required to return an integer, but here I didn\'t put in return 0; and and it compiled w

相关标签:
4条回答
  • 2020-12-02 23:07

    3.6.1 Main function

    ....

    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() { /* ... */ }
    

    and

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

    .... and it continues to add ...

    5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

    attempting to find an online copy of the C++ standard so I could quote this passage I found a blog post that quotes all the right bits better than I could.

    0 讨论(0)
  • 2020-12-02 23:13

    This is part of the C++ language standard. An implicit return 0 is generated for you if there's no explicit return statement in main.

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

    I'm pretty sure VC++ just inserts a return 0 if you don't include one in main functions. The same thing can happen with functions too, but in those cases at least you'll get a warning.

    0 讨论(0)
  • 2020-12-02 23:27

    Section 6.6.3/2 states- "Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.".

    An example is the code below which at best gives warning on VS 2010/g++

    int f(){
       if(0){
          if(1)
             return true;
       }
    }
    
    int main(){
       f();
    }
    

    So the whole point is that 'main' is special as the previous responses have pointed out.

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