Dividing by zero in a constant expression

后端 未结 5 510
有刺的猬
有刺的猬 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:55

    From C standard draft (N1570):

    6.5.5 Multiplicative operators

    ...

    1. The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

    And about undefined behaviour in chapter 3. Terms, definitions, and symbols:

    3.4.3

    1. undefined behavior
      behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
    2. NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

    So crashing the compiler is allowed.

提交回复
热议问题