What happens if you don't return a value in C++?

后端 未结 6 798
南方客
南方客 2020-12-28 18:56

Yesterday, I found myself writing code like this:

SomeStruct getSomeStruct()
{
    SomeStruct input;

    cin >> input.x;
    cin >> input.y;
}
<         


        
6条回答
  •  盖世英雄少女心
    2020-12-28 19:19

    I find this interesting. With default options used, the following compilers have the following behavior when compiling the GetSomeStruct() function:

    • Microsoft VC, all versions (since VC6 anyway):

      error C4716: 'getSomeStruct' : must return a value

    • Digital Mars:

      Warning 18: implied return of getSomeStruct at closing '}' does not return value

    • Comeau:

      warning: missing return statement at end of non-void function "getSomeStruct"

    • gcc:

      no error or warning

    Given the following couple of sentences from the standard (6.6.3 Paragraph 2):

    A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). ... 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.

    I would say there's little reason for a compiler not to give an error in this case. Why do so many compilers give only a warning or no diagnostic at all?

提交回复
热议问题