Home > Net >  Why isn't the cout overflow in this situation?
Why isn't the cout overflow in this situation?

Time:09-17

I have the following code patch running on my ubuntu20.04, compiled by gcc-9.

#include <iostream>

int main()
{
    uint16_t a = 0xFFFF;
    uint16_t b = 1;

    uint16_t ret = a   b;
    std::cout << a   b << std::endl;
    std::cout << ret << std::endl;
}

I expect both of the results are overflowed, but the running results show that only the second one overflows and the first one can get correct result.

What makes them behave differently. The right value of the operation should also be uint16_t, so why the first cout can get the right result?

P.S., when I change the type from uint16_t to uint32_t, both of them are overflowed.

CodePudding user response:

When you do a b the operands will undergo arithmetic conversions which will promote the values to int types.

So a b is really something like static_cast<int>(a) static_cast<int>(b) and the result will of course be an int.

Promotion only happens with types smaller than int (so short or char). Values that already are int (or larger) will not be promoted.

  • Related