gpt4 book ai didi

c++ - 未评估的除以 0 是未定义的行为吗?

转载 作者:IT老高 更新时间:2023-10-28 13:21:23 28 4
gpt4 key购买 nike

我与一些同事对以下代码存在分歧:

int foo ( int a, int b )
{
return b > 0 ? a / b : a;
}

此代码是否表现出未定义的行为?

编辑:分歧始于过度渴望优化编译器中的一个错误,其中 b > 0 检查已被优化。

最佳答案

没有。


引自 N4140:

§5.16 [expr.cond]/1

Conditional expressions group right-to-left. The first expression is contextually converted to bool. It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated.

进一步:

§5 [expr]/4

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

这显然不会在这里发生。同一段在注释中明确提到除以零,虽然它是非规范性的,但它更清楚地表明它与这种情况有关:

[ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]


还有间接证据强化了上述观点:条件运算符用于有条件地使行为未定义。

§8.5 [dcl.init]/12.3

int f(bool b) {
unsigned char c;
unsigned char d = c; // OK, d has an indeterminate value
int e = d; // undefined behavior
return b ? d : 0; // undefined behavior if b is true
}

在上面的示例中,使用 d 来初始化 int(或 unsigned char 以外的任何内容)是未定义的。然而,它明确指出只有在评估 UB 分支时才会发生 UB。


脱离语言律师的观点:如果这可能是 UB,那么任何除法都可以被视为 UB,因为除数可能为 0。这不是规则的精神。

关于c++ - 未评估的除以 0 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40172606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com