Boost logo

Boost :

Subject: Re: [boost] safe integer library -- the scope
From: Robert Ramey (ramey_at_[hidden])
Date: 2015-12-11 20:50:13


On 12/11/15 5:01 PM, Pete Bartlett wrote:
>
>> safe_integer_range<-100, 100> a, x, b, y;
>> y = a * x + b;
>>
>> Then it can be known at compile time that y can never overflow so no runtime checking is required.
>
> This is the second time you've written something like this - in the PDF

The example in the proposal was confusing - I've since corrected it.

you said that squaring an int8_t didn't overflow.

int8_t x = 100

int y = x * x; // x * x cannot overflow

clearly it depends on the values of a,x,b which in general are only
known at runtime.
So what do you mean there are no runtime checks?

The reason x * x cannot overflow is the C++ type promotion rules for
expressions. signed operands in binary expressions which are smaller
than than int are promoted to int. Then the operation (multiplication is
performed. Since the maximum value that int8_t can hold is 255 and
255 * 255 is less than the maximum value that an int can hold, the
multiplication can never overflow and there is no need to check it.

Robert Ramey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk