Boost logo

Boost :

Subject: Re: [boost] safe integer library -- the scope
From: Andrzej Krzemienski (akrzemi1_at_[hidden])
Date: 2015-12-14 03:31:08


2015-12-12 3:10 GMT+01:00 Robert Ramey <ramey_at_[hidden]>:

> On 12/11/15 5:50 PM, Robert Ramey wrote:
> To belabor the point, consider this little program:
>
> #include <iostream>
> #include <cstdint>
>
> using namespace std;
>
> int main(){
> int8_t x = 100;
> int y = x * x;
> cout << y << endl;
>
> uint32_t z1 = 100;
> int8_t z2 = -100;
> auto y2 = z1 * z2;
> cout << y2 << endl;
>
> return 0;
> }
>
> which prints out:
>
> 10000
> 4294957296
>
> This is due to the application of the C++ type promotion rules.
>
> Is it any reason that C++ drives people crazy?
>

While I do agree with your point of view, I do not agree with the choice of
the example. I would say that the problem here comes from the fact that
that an unsigned type is used for anything else but a bit-set. To fix it,
and to avoid such problems in the future, one does not necessarily have to
use a library, but simply apply the rule "never use unsigned to represent
integer numbers, even the positive ones".

And it would work for some time, until I start playing with bigger numbers:

int main(){
    int8_t x = 100;
    int y = x * x;
    std::cout << y << std::endl;

    int z1 = 1000000000;
    int z2 = 1000000000;
    auto y2 = z1 * z2; // overflow
    std::cout << y2 << std::endl;

    return 0;
}

And at this point I need safe<int> (or a BigInt).

Regards,
&rzej


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