Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
xmllmx Avatar asked Dec 07 '25 03:12

xmllmx


2 Answers

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.

like image 57
Dietmar Kühl Avatar answered Dec 09 '25 04:12

Dietmar Kühl


It's undefined behavior, but the compiler isn't required to report this.

C++11(ISO/IEC 14882:2011) §6.6.3 The return statement

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). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object (12.2). 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.

like image 44
Yu Hao Avatar answered Dec 09 '25 03:12

Yu Hao