tags:

views:

114

answers:

3

As expected, the compiler (VisualStudio 2008) will give a warning

warning C4715: 'doSomethingWith' : not all control paths return a value

when compiling the following code:

int doSomethingWith(int value)
{
    int returnValue = 3;
    bool condition = false;

    if(condition)
        // returnValue += value; // DOH

    return returnValue;
}

int main(int argc, char* argv[])
{
    int foo = 10;
    int result = doSomethingWith(foo);
    return 0;
}

But the program runs just fine. The return value of function doSomethingWith() is 0.

Is is just undefined behavior, or is there a certain rule how the result value is created/computed at runtime. What happens with non-POD datatypes as return value?

+9  A: 

It is Undefined behaviour as specified in the ISO C++ standard section 6.6.3:

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.

piotr
Specific wordings:— Flowing off the end of a function is equivalent to a `return` with no value; this results in undefined behaviorin a value-returning function.
KennyTM
'main' function is an exception to that rule. In nabulke code, last 'main' function line is redundant.
fnieto
+2  A: 

Not returning a value from a value-returning function leads to undefined behavior.

codaddict
+2  A: 

For x86 processors the standard calling convention puts the return value to the EAX register. Practically it means that for most compilers if we reach the end of the function without returning the result of the last math operation will be returned. You can not rely on it and it is not portable.

http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl

Muxecoid