简体   繁体   中英

Conditional branches

Why this piece of code compiles?

#include <iostream>

int foo(int x)
{
   if(x == 10)
     return x*10;
}

int main()
{
int a;
std::cin>>a;
std::cout<<foo(a)<<'\n';
}

The compiler shouldn't give me an error like "not all code paths returns a value"? What happens/returns my function when x isn't equal to ten?

The result is undefined, so the compiler is free to choose -- you probably get what happens to sit at the appropriate stack address where the caller expects the result. Activate compiler warnings, and your compiler will inform you about your omission.

The compiler is not required to give you an error in this circumstance. Many will, some will only issue warnings. Some apparently won't notice.

This is because it's possible that your code ensures outside of this function that the condition will always be true. Therefore, it isn't necessarily bad (though it almost always is, which is why most compilers will issue at least a warning).

The specification will state that the result of exiting a function that should return a value but doesn't is undefined behavior. A value may be returned. Or the program might crash. Or anything might happen. It's undefined.

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