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

自闭症网瘾萝莉.ら 提交于 2020-11-29 09:27:45

问题


I came across the following code that 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 this compile if there is no return statement at the end of the method?


回答1:


This is to support backwards compatibility with C which did not strictly require a return from all functions. In those cases you were simply left with whatever the last value in the return position (stack or register).

If this is compiling without warning though you likely don't have your error level set high enough. Most compilers will warn about this now.




回答2:


It's possible to write code that is guaranteed to always return a value, but the compiler might not be able to figure that out. One trivial example would be:

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's possible that all 3 if statements evaluate to false, in which case control would fall off the end of the function, returning an undefined result. Mathematically, though, we know it's impossible for that to happen, so this function has defined behavior.

Yes, a smarter compiler might be able to figure this out, but imagine that of integer 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 that out.

The reason this is allowed is for compatibility with C, and the reason that C allows it is for compatibility with legacy C code that was written before C was standardized (pre-ANSI). There was code that did exactly this, so to allow such code to remain valid and error-free, the C standard permitted this. Letting control fall off a function without returning a value is still undefined behavior, though.

Any decent compiler should provide a warning about this; depending on your compiler, you may have to turn your warning level way up. I believe the option for this warning with gcc is -Wextra, which also includes a bunch of other warnings.




回答3:


Set the warning level to 4 and tryout.Not all control path returns a value is the warning I remember getting this warning.




回答4:


Probably your particular compiler is not doing as good flow control analysis as it should.

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



来源:https://stackoverflow.com/questions/1400954/how-does-this-c-code-compile-without-an-end-return-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!