Re: Good way to write integer overflow checks?
On 11/9/2013 4:00 PM, Alf P. Steinbach wrote:
On 09.11.2013 20:26, Victor Bazarov wrote:
On 11/9/2013 10:28 AM, Alf P. Steinbach wrote:
This code is in support of some API functionality:
[code]
inline
auto can_inflate( gdi::Rect const& r, int const dx, int const dy )
-> bool
{
CPPX_XASSERT( INT_MIN/2 < dx && dx < INT_MAX/2 );
CPPX_XASSERT( INT_MIN/2 < dy && dy < INT_MAX/2 );
typedef unsigned long Unsigned_long;
auto const msb = ULONG_MAX - (ULONG_MAX >> 1);
return
(r.left & msb) == ((Unsigned_long( r.left ) - dx) & msb) &&
(r.top & msb) == ((Unsigned_long( r.top ) - dy) & msb) &&
(r.right & msb) == ((Unsigned_long( r.right ) + dx) & msb) &&
(r.bottom & msb) == ((Unsigned_long( r.bottom ) + dy) & msb);
}
[/code]
Can this be written in an even gooder way, for bestest possible code?
Disclaimer: the code has not been tested or even called.
What is the code supposed to do? Are you checking if the size of 'r' is
not going to under- or overflow if you add dx and dy to it?
Yes.
Isn't this the usual way to check if (b+a) is not going to overflow:
if (INT_MAX - b > a) // a+b will NOT overflow
Don't know, but that expression has formally Undefined Behavior when b
is a negative signed integer,
Yes, but that is easy to check itself, is it not?
> since then the checking itself overflows.
It won't if you don't do *that particular checking* for negative b, now,
will it?
So, at least if one's not going to rely on two's complement form
wrap-around (g++ can be made to trap on that), I /think/ it would yield
more verbose code, possibly also more complicated?
You mean, more difficult to read and understand than your fiddling with
the bits? Wrap it into smaller functions, name them appropriately, and
you shouldn't have any problem... Or don't.<shrug>
If you wanted an argument, you should have said so. Although,
admittedly, upon re-reading your message, I ought to guessed as much
from the use of "gooder" and "bestest"... You got me.
V
--
I do not respond to top-posted replies, please don't ask