Re:Understanding Integer Overflow in C/C++ (2012) [pdf]
by Asooka on Saturday July 09, 2016 @02:06PM
(#12062534)
AFAIK the case for undefined integer overflow is optimisations regarding loop termination, carry bit handling, and usage of 64-bit vs 32-bit registers. In light of that can't we say that "The compiler may perform signed integer arithmetic using registers larger than the type's bits and truncate the result when writing to memory"? So e.g.
Another idea I haven't seen used enough is to put values in 64-bit doubles, do your arithmetic that way and check if the final value fits in your integer type. As long as you restrict yourself to adding, subtracting and multiplying you'll get an exact result back (ok unless you run on a buggy pentium from over 25 years ago, but I think all those were recalled). A problem you have to watch out for is if you've entered the range where your ulp is larger than 1 and your math gets inexact.
[ Parent
| on HN ]
Re:Understanding Integer Overflow in C/C++ (2012) [pdf]
by nayuki on Saturday July 09, 2016 @04:05PM
(#12063055)
> 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.
Re:Understanding Integer Overflow in C/C++ (2012) [pdf]
by nkurz on Saturday July 09, 2016 @06:27PM
(#12063634)
I 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.
Re:Understanding Integer Overflow in C/C++ (2012) [pdf]
by ArkyBeagle on Saturday July 09, 2016 @03:55PM
(#12063002)
I use float/double float values A Lot these days for arithmetic. So that reduces integer use to values read over a comms line or read otherwise from hardware.
Of course, floats have their own quantum of grief.