在常数表达式中除以零 [英] Dividing by zero in a constant expression

查看:102
本文介绍了在常数表达式中除以零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用一个常量表达式除以零,我的玩具编译器将崩溃:

My toy compiler crashes if I divide by zero in a constant expression:

int x = 1 / 0;

C和/或C ++标准是否允许这种行为?

Is this behaviour allowed by the C and/or C++ standards?

推荐答案

仅出现 1/0 不会使编译器崩溃.最多可以假定该表达式将永远不会被求值,因此,执行将永远不会到达给定的行.

The mere presence of 1 / 0 does not permit the compiler to crash. At most, it is permitted to assume that the expression will never be evaluated, and thus, that execution will never reach the given line.

如果保证对表达式进行求值,则该标准对程序或编译器没有任何要求.然后编译器可能会崩溃.

If the expression is guaranteed to be evaluated, the standard imposes no requirements on the program or compiler. Then the compiler can crash.

C11标准给出了 1/0 的显式示例.code>在未评估时被定义为行为:

The C11 standard gives an explicit example of 1 / 0 being defined behavior when unevaluated:

因此,在以下初始化中,

Thus, in the following initialization,

        static int i = 2 || 1 / 0;

该表达式是值为1的有效整数常量表达式.

the expression is a valid integer constant expression with value one.

第6.6节,脚注118.

Section 6.6, footnote 118.

在约束下的C11标准的6.6节说,

  1. 常量表达式不得包含赋值,递增,递减,函数调用或逗号运算符,除非它们包含在未求值的子表达式中.
  2. 每个常量表达式的求值均应在其类型的可表示值范围内.

由于1/0在int可表示的值范围内未求出常量,因此1/0不是常量表达式.这是关于什么算作常量表达式的规则,例如关于在其中没有赋值的规则.您可以看到至少对于C ++, Clang不会将1/0视为常量表达式:

Since 1/0 does not evaluate to a constant in the range of values representable by an int, 1/0 is not a constant expression. This is a rule about what counts as a constant expression, like the rule about not having assignments in it. You can see that at least for C++, Clang doesn't consider 1/0 a constant expression:

prog.cc:3:18: error: constexpr variable 'x' must be initialized by a constant expression
   constexpr int x = 1/ 0 ;
                 ^   ~~~~

将未评估的1/0设为UB并没有多大意义.

(x == 0)?x:1/x 定义明确,即使x为0且评估1/x为UB.如果是(0 == 0)的情况?0:1/0 是UB,那是胡说八道.

It wouldn't make much sense for an unevaluated 1 / 0 to be UB.

(x == 0) ? x : 1 / x is perfectly well-defined, even if x is 0 and evaluating 1/x is UB. If it were the case that (0 == 0) ? 0 : 1 / 0 were UB, that would be nonsense.

这篇关于在常数表达式中除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆