Dividing by zero in a constant expression

后端 未结 5 461
有刺的猬
有刺的猬 2021-02-02 06:47

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

int x = 1 / 0;

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

5条回答
  •  逝去的感伤
    2021-02-02 06:57

    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.

    1 / 0 is only UB if evaluated.

    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;
    

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

    Section 6.6, footnote 118.

    1 / 0 is not a constant expression.

    Section 6.6 of the C11 standard, under Constraints, says

    1. Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.
    2. Each constant expression shall evaluate to a constant that is in the range of representable values for its type.

    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 ;
                     ^   ~~~~
    

    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.

提交回复
热议问题