c++ - 没有非空函数的返回语句是否是未定义的行为,其中控制永远不会结束?

我正在使用列出的书籍学习 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 语句时会发生什么。第二个陈述是关于当控制流完全不退出函数时会发生什么。对 exitstd::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/

相关文章:

laravel - 如何通过单击进入 vs 代码中的一个类

r - 取消列出嵌套列表的倒数第二个列表

visual-studio - Visual Studio 2022 无法添加服务引用且没有程序集引

amazon-web-services - 如何将事件从 EventBridge 发送到 Lambd

javascript - 使用javascript更新foreach循环中的数组对象

python - 给定一个数字,找到到达它的序列

javascript - 我将如何在 P5.js 的 Canvas 上的两个位置之间创建点?

javascript - 找时间在一张图中写一个数字

typescript - 我可以根据参数更改返回类型吗

reactjs - webpack-cli : Invalid options object. De