How does this C ++ code compile without a return end statement?

I came across the following code which compiles fine (using Visual Studio 2005):

SomeObject SomeClass::getSomeThing()
{
    for each (SomeObject something in someMemberCollection)
    {
        if ( something.data == 0 )
        {
            return something;
        }
    }
    // No return statement here
}

      

Why does it compile if there is no return statement at the end of the method?

+2


source to share


4 answers


This is backward compatibility support with C, which did not require strict backtracking from all functions. In these cases, you just have any last value in the return position (stack or register).



If it compiles without warning, although you probably don't have a high enough error rate. Most compilers will warn about this now.

+20


source


Set the warning level to 4 and try it. Not all control paths return a value, this is the warning I remember getting this warning.



+5


source


It is possible to write code that is guaranteed to always return a value, but the compiler may not be able to figure it out. One simple example:

int func(int x)
{
    if(x > 0)
        return 1;
    else if(x == 0)
        return 0;
    else if(x < 0)
        return -1;
}

      

As far as the compiler is concerned, it is possible that all 3 statements if

evaluate to false

, in which case control will fall away from the end of the function, returning undefined. Mathematically, however, we know that it is not possible for this to happen, so this function defined the behavior.

Yes, a smarter compiler might figure this out, but imagine that out of whole comparisons, we had calls to external functions defined in a separate translation unit. Then, as humans, we can prove that all control paths return values, but the compiler certainly can't figure it out.

The reason for this is C compatibility, and the reason C allows it to be compatible with legacy C code that was written before C was standardized (before ANSI). There was code that did just that, so to keep this code valid and error-free, the C standard allowed it. However, if control is disconnected from the function without returning a value, it is still undefined.

Any decent compiler should warn about this; depending on your compiler, you may need to raise the warning level. I believe the option for this warning with gcc is this -Wextra

, which includes many other warnings as well.

+5


source


It is likely your particular compiler is not doing as good a flow control analysis as it should.

What version of the compiler are you using and what switches are you using to compile with?

0


source







All Articles