Compiler optimization uses the As-if rule.
As-if rule
Allows any code transformations that do not alter the programโs observed behavior.
So, the compiler can optimize this. Check out the following modified sample :
#include <iostream> int main() { int y = 1; int x = (y=1/0, 2); std::cout << x << std::endl; //std::cout << y << std::endl; }
Commenting out the last line compiles and correctly executes this code when uncommenting, which gives the expected undefined behavior.
As @jogojapan correctly points out,
It is important to note that compiler optimization is not guaranteed by the standard, and division by zero is undefined behavior. So this code has undefined behavior. Whether the observed behavior is observed due to the fact that the compiler optimizes division by zero or due to undefined behavior, which we will never know about. Technically, this behavior is undefined anyway.
source share