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.
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).
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.
Overflow is a phenomenon where operations on 2 numbers exceeds the maximum (or goes below the minimum) value the data type can have.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With