简体   繁体   English

有条件的分支

[英]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? 当x不等于10时,会发生什么/返回我的函数?

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. 这是因为您的代码可能会在此函数之外确保条件始终为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. 这是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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