Why doesn't 'd /= d' throw a division by zero exception when d == 0?

后端 未结 4 1138
深忆病人
深忆病人 2021-02-02 04:50

I don\'t quite understand why I don\'t get a division by zero exception:

int d = 0;
d /= d;

I expected

4条回答
  •  别那么骄傲
    2021-02-02 05:43

    The behaviour of integer division by zero is undefined by the C++ standard. It is not required to throw an exception.

    (Floating point division by zero is also undefined but IEEE754 defines it.)

    Your compiler is optimising d /= d to, effectively d = 1 which is a reasonable choice to make. It's allowed to make this optimisation since it's allowed to assume there is no undefined behaviour in your code - that is d cannot possibly be zero.

提交回复
热议问题