c++c++11visual-c++

No warnings for that function int f() doesn't return any value?


struct A
{
    int f()
    {} // Notice here! 
};

int main()
{
    A a;
    a = a;
}

My compiler is the latest VC++ compiler (Visual Studio 2013 Preview)

The function A::f doesn't return any value; but no compiler warnings or errors! Why?


Solution

  • The C++ compiler isn't required to issue a diagnostic on not returning a value but if your program ever exits a non-void function (other than main()) without a return statement by falling off its end, the behavior is undefined. That is, it is legal for the compiler to compile the code but it won't be legal to ever call this function f() as it will result in undefined behavior.

    The main reason for not requiring the compiler to issue a diagnostic, i.e., to make the behavior undefined, is that it sometimes impossible to tell whether a function will, indeed, return from a function. For example, imagine a function like that:

    int f() {
        if(somecondition) { return 0; }
        this_function_throws();
    }
    

    where this_function_throws() is in a separate translation unit and always ends up throwing an exception.