简体   繁体   中英

c++ return value

I have the following code in c++:

    int fff ( int a , int b )
{
   if (a>b )
      return 0;
   else a+b ; 
}

although I didn't write 'return' after else it does not make error ! < br/> in main() when I wrote:

cout<<fff(1,2);

it printed 1 ? How did that happened
can any one Explain that ?

This what is called undefined behavior . Anything can happen.

C++ does not require you to always return a value at the end of a function, because it's possible to write code that never gets there:

int fff ( int a , int b )
{
   if (a>b )
      return 0;
   else return a+b;

   // still no return at end of function
   // syntactically, just as bad as original example
   // semantically, nothing bad can happen
}

However, the compiler cannot determine if you never get to the end of the function, and the most it can do is give a warning. It's up to you to avoid falling off the end without a return .

And if you do, you might get a random value, or you might crash.

$6.6.3/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."

A compiler may or may not diagnose such a condition.

Here

else a + b;

is treated as an expression without any side effect.

the "random" return vaule is determined by the CPU register value after the call, since the register is 1 after the call, so the value is 1.

If you change you code, the function will return diffrent value.

A good compiler (eg gcc) will issue a warning if you make such a mistake, and have a command line switch to return a non-zero error status if any warnings were encountered. This is undefined behaviour: the result you're seeing is whatever value happened to be in the place that the compiler would normally expect a function returning int to use: for example, the accumulator register or some spot on the stack. Your code doesn't copy a+b into that location, so whatever was last put in there will be seen instead. Still, you're not even guaranteed to get a result - some compiler/architecture might do something that can crash the machine if the function didn't have a return statement: for example - pop() a value from the stack on the assumption that return has pushed one - future uses of the stack (including reading function-return addresses) could then get results from the memory address above or below the intended one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM