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

后端 未结 4 1201
深忆病人
深忆病人 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:26

    C++ does not have a "Division by Zero" Exception to catch. The behavior you're observing is the result of Compiler optimizations:

    1. The compiler assumes Undefined Behavior doesn't happen
    2. Division by Zero in C++ is undefined behavior
    3. Therefore, code which can cause a Division by Zero is presumed to not do so.
      • And, code which must cause a Division by Zero is presumed to never happen
    4. Therefore, the compiler deduces that because Undefined Behavior doesn't happen, then the conditions for Undefined Behavior in this code (d == 0) must not happen
    5. Therefore, d / d must always equal 1.

    However...

    We can force the compiler to trigger a "real" division by zero with a minor tweak to your code.

    volatile int d = 0;
    d /= d; //What happens?
    

    So now the question remains: now that we've basically forced the compiler to allow this to happen, what happens? It's undefined behavior—but we've now prevented the compiler from optimizing around this undefined behavior.

    Mostly, it depends on the target environment. This will not trigger a software exception, but it can (depending on the target CPU) trigger a Hardware Exception (an Integer-Divide-by-Zero), which cannot be caught in the traditional manner a software exception can be caught. This is definitely the case for an x86 CPU, and most other (but not all!) architectures.

    There are, however, methods of dealing with the hardware exception (if it occurs) instead of just letting the program crash: look at this post for some methods that might be applicable: Catching exception: divide by zero. Note they vary from compiler to compiler.

提交回复
热议问题