3 ms·
> Asooka wrote: // i.e. you can always test if two positive values overflow with ((a + b) & 0x7F..F) > a This is bad advice. The act of computing (a + b)
by nayuki 10y ago
> Asooka wrote:
// i.e. you can always test if two positive values overflow with
((a + b) & 0x7F..F) > a
This is bad advice. The act of computing (a + b) is undefined behavior. Masking it afterward will not save you against a strict compiler that exploits (or traps) all undefined behaviors.
- nkurz 10y agoI think the 'Asooka' is aware of this, and was not offering advice. Rather, he was proposing that the world would be simpler if the specs were changed so that signed addition never resulted in undefined behavior. In this simpler counterfactual world, his test would work. In our current easier to optimize world, it would not.
- Asooka 10y agoYes exactly, my point was to allow the compiler to do the addition using any registers it likes, with the only requirement being that the value is truncated when written to memory. This is less defined than "implementation defined", because a single implementation can decide to write the value to memory at an arbitrary time. But it's still better than undefined behaviour, since signed overflow is allowed to happen , just with circumstance defined behaviour. In general I would say that compilers should allow you to say "please treat undefined behaviours as platform defined". Few people write C that has to be portable between 2's complement integer processors and Minecraft logic blocks and those who do, I expect to use a fairly robust suite of static analysers and tests to guard against undefined behaviour and platform differences.