我正在使用列出的书籍学习 C++ here .特别是,我读到从非 void 函数的末尾流出是未定义的行为。然后我看了this回答说:
In C++ just flowing off the end of a value returning function is always undefined behavior (regardless of whether the function's result is used by the calling code). In C this causes undefined behavior only if the calling code tries to use the returned value.
但是在this我读的答案:
It is legal under C/C++ to not return from a function that claims to return something.
正如您在第一个引用的答案中看到的那样,用户说在 C++ 中它始终是 UB,但第二个引用的答案说它是合法的。它们似乎相互矛盾。
上面引用的哪个答案在 C++ 中是正确的?
我还有以下 C++ 示例:
int func(int a, int b)
{
if(a > b)
{
return a;
}
else if(a < b)
{
return b;
}
}
int main()
{
int x =0, y =0;
std::cin>> x >> y;
if(x!=y)
{
func(x,y); //Question 1: IS THIS UB?
std::cout<<"max is: "<<func(x,y); //Question 2: IS THIS UB?
}
else
{
std::cout<<"both are equal"<<std::endl;
}
return 0;
}
我在上面的代码注释中提到了上面给出的代码片段中的 2 个问题。
从代码中可以看出,控制永远不会越过函数 func
的末尾,因为 a
永远不会等于 b
在函数中,因为我已经在 main
中分别检查了该条件。
最佳答案
这两种说法并不矛盾。
第一个语句是关于当控制流退出非void
函数而不执行return
语句时会发生什么。第二个陈述是关于当控制流完全不退出函数时会发生什么。对 exit
或 std::terminate
等函数的调用永远不会让控制流继续进行到调用这些函数的点之后。
但这与返回值的性质无关。
当非 void
函数在没有显式 return
语句(或 throw
)的情况下没有事情要做时程序的行为。或者 co_return
这些天)由 [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.
https://stackoverflow.com/questions/71507110/