开发者

Assignment to non-void functions (returning nothing) can change the values?

I encountered this problem in my program which was creating problems. so let me explain it by a example:

#include<iostream>

int func(){
        if(1==0) return 100;
}

int main(){

        int x=99;
        x= func();
        std::cout<<"Value of x: " << x <<std:开发者_JAVA百科:endl;
}

I had thought the output will be 99 but output is 0, so what's going on here?


It is causing undefined behavior. The condition is false so there is no return value from the function.


You have undefined behavior because your function is declared to return an int but the execution path through the function never reaches a return statement.

In C++ it is illegal to exit a function defined as returning a non-void type other than via a return statement with an argument.

ISO/IEC 14882:2003 6.6.3 [stmt.return] / 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.


From C++03 6.6.3/2 "The return statement":

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.

Since your function flows "off the end", it's UB and you can expect nothing (or anything).

As a side note: this is slightly different than in C, where flowing off the end of a function that is declared to return something is not UB in itself - it becomes UB only if the caller uses the result of a function that does that.

In other words, using your example, in C++ you have UB at the moment func() returns, whether that result is assigned to x or not. In C it's UB only because you assign the result to x.


It depends on the compiler you are using.

When you compile this code, a normal compiler will cause a warning similar to:

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

It looks like your compiler is placing a statement that returns 0 when it doesn't find a return statement on the way out. So, x will be assigned 0.


As everyone else has said, you have undefined behavior. As for how to fix/identify it, one way would be to use warning flags when compiling your program. If you run your code in codepad, it's easy to see the issue:

http://codepad.org/MXDSniWw

cc1plus: warnings being treated as errors
In function 'int func()':
Line 5: warning: control reaches end of non-void function

In func(), your if loop is never true, but you haven't specified any other return value, so you have undefined behavior. Adding return 0; after the if.. will fix the issue.


So you expect a 99, the safest bet is to pass x by reference:

#include<iostream>

void func(int& a){
    if (1==0)
        a = 100;
}

int main(){
    int x(99);
    func(x);
    std::cout << "Value of x: " << x << std::endl;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜