3 ms·
Your reasoning is incorrect. Here is how I reason about it. Division by zero is undefined behavior. The compiler can assume that it will not happen. If the di
by nayuki 2y ago
Your reasoning is incorrect. Here is how I reason about it.
Division by zero is undefined behavior. The compiler can assume that it will not happen.
If the divisor is not zero, then the calculation has no side effects. The compiler may reorder the division above the print, because it would have no observable difference in behavior. This could be useful because division has a high latency, so it pays to start the operation as soon as the operand values are known.
If the divisor is zero, the UB says that there is no requirement on how it's compiled, so reordering the division above the print is legal.
- asdfaoeu 2y agoHow can it both have no side effects and have undefined behaviour?
- masklinn 2y agoBy being declared as that? Division has no side effects, and division by 0 is UB. UBs only occur in invalid programs, so behaviour in case of UB is not relevant to a discussion of side effects or their lack thereof, in language terms these are not programs at all.
- asdfaoeu 2y agoIf print statement never completes then it is a well defined program. Because there will be no division by zero.
- sapiogram 2y agoBoth statements don't need to be true. The compiler just has to prove that at least one of the statements will always be true.
- asdfaoeu 2y agoTrue but it only has no side effects if it's well defined. The compiler can assume it's well defined but only if it's executed.
- gpderetta 2y agoconst int div = 0; if(div) { return 1/div; } return 0; The statement at line 3 would have undefined behaviour, yet is never reached so this is a perfectly legal program and any transformation that hoists it above the check is invalid. If you replace 'if(div)' with an opaque function call, that doesn't change anything as the function might never exit the program, never return, long jump or return via an exception.