Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow expected but adding two bytes does not

Update

Can anyone explain the reason for promoting uint8_t to int? What are the use cases for this behavior? And can I prevent the promoting?


I have these very simple code snippets which add two integer types together and print the result. I have compiled those without any optimization with g++ --std=c++11 main.cpp -o test

int main()
{
    uint8_t a = 200, b = 100;
    uint16_t result = (a + b);

    printf("result is %d\n", result);
}

Outputs:

result is 300

I would have expected (a + b) to evaluate to 44 because they are both of an 8-bit type and should overflow. But instead I get the unexpected result of 300.


If I re-run the same test with uint32_t and uint64_t, it is overflowing as expected:

int main()
{
    uint32_t a = UINT_MAX, b = UINT_MAX;
    uint64_t result = (a + b);

    printf("result is %ld\n", result);
}

Outputs:

result is 4294967294

Now I can't tell why uint8_t is treated differently to uint32_t.

like image 235
bricklore Avatar asked Dec 19 '25 04:12

bricklore


1 Answers

integral types smaller than int are promoted to int when operations are performed on them

like image 152
pm100 Avatar answered Dec 20 '25 21:12

pm100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!