6 ms·
If you don't go by the spec, what do you go by? Intuition? What if yours is different from someone else's? In this case as well, acknowledging that signed inte
by stouset 11y ago
If you don't go by the spec, what do you go by? Intuition? What if yours is different from someone else's?
In this case as well, acknowledging that signed integer overflow is undefined behavior allows for more consistent behavior in certain circumstances. For instance, the compiler knows that `x < x + c`, where `c > 0`, and optimize it to `true`. Even if you don't care about the optimization, is it not equally surprising that such a statement could ever be `false`?
No matter which way you go, some behavior is going to be surprising. And in these scenarios, the only plausible thing to do so is to follow the standard, so at least there's a consistent ideal that everyone's intuitions can converge to, which is crucially important. Each compiler implementing a different C-alike standard just leads to more confusion.
- Spivak 11y agoMaybe a better way to illustrate the surprising behavior is that if (x < x + c) { // block } if (0 < c) { // block } are not equivalent statements if you add overflow wrapping into the spec. What if the processor your application is running on doesn't do two's compliment arithmetic? Does gcc need to emulate this behavior to comply with the spec?
- userbinator 11y agoIf you don't go by the spec, what do you go by? To quote the standard, "a documented manner characteristic of the environment." If the machine is two's complement (which is the vast majority of them), then you'd expect that behaviour. If it's sign-magnitude or one's complement or saturating, then the behaviour would be different but still consistent. Even if you don't care about the optimization, is it not equally surprising that such a statement could ever be `false`? Overflows wrapping around is not surprising, it's what decades of computing hardware (or centuries if you include mechanical calculators like https://en.wikipedia.org/wiki/Pascal%27s_Calculator https://en.wikipedia.org/wiki/Pascal%27s_Calculator ) have always done.
- stouset 11y ago> If the machine is two's complement (which is the vast majority of them), then you'd expect that behaviour. If it's sign-magnitude or one's complement or saturating, then the behaviour would be different but still consistent. How is this different in practice from undefined behavior, other than the compiler can't take advantage of it for optimizations?