I don't quite understand why I don't get a division by zero exception:
int d = 0;
d /= d;
I expected to get a division by zero exception but instead d == 1
.
Why doesn't d /= d
throw a division by zero exception when d == 0
?
C++ does not have a "Division by Zero" Exception to catch. The behavior you're observing is the result of Compiler optimizations:
d == 0
) must not happend / d
must always equal 1.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.