Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the cout overflow in this situation?

Tags:

c++

c++11

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.

like image 968
X.S. Wang Avatar asked Sep 09 '21 13:09

X.S. Wang


People also ask

How to check for overflow and underflow?

Detecting Overflow and Underflow We can detect overflow and underflow by checking, if b >= 0, that a > MAX - b, otherwise with b < 0, that a < MIN - b. The reason this works is that, if b is greater than or equal to 0, we can safely subtract it from MAX (if it were negative, subtracting it would cause an overflow).

What is underflow and overflow in c++?

Overflow and underflow are general terms. They describe the situation when something becomes too big or too small to be processed correctly or stored in the space allocated to it correctly.

What is the overflow in C++?

Overflow is a phenomenon where operations on 2 numbers exceeds the maximum (or goes below the minimum) value the data type can have.


1 Answers

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.

like image 123
Some programmer dude Avatar answered Nov 04 '22 07:11

Some programmer dude