What do arithmetic underflow and overflow mean in C programming?
Storing values that are too low in an integer variable (e.g., attempting to store −1 in an unsigned integer) is properly referred to as integer overflow, or more broadly, integer wraparound. The term underflow normally refers to floating point numbers only, which is a separate issue.
(Arithmetic) Integer OverflowsAn integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
Simply put, overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable. If the (absolute) value is too big, we call it overflow, if the value is too small, we call it underflow.
The situation where an integer outside the allowed range requires more bits than can be stored is called an overflow. Similarly, with real numbers, an exponent that is too small to be stored causes an underflow.
Overflow
From http://en.wikipedia.org/wiki/Arithmetic_overflow:
the condition that occurs when a calculation produces a result that is greater in magnitude than that which a given register or storage location can store or represent.
So, for instance:
uint32_t x = 1UL << 31; x *= 2; // Overflow!
Note that as @R mentions in a comment below, the C standard suggests:
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
Of course, this is a fairly idiosyncratic definition of "overflow". Most people would refer to modulo reduction (i.e wrap-around) as "overflow".
Underflow
From http://en.wikipedia.org/wiki/Arithmetic_underflow:
the condition in a computer program that can occur when the true result of a floating point operation is smaller in magnitude (that is, closer to zero) than the smallest value representable as a normal floating point number in the target datatype.
So, for instance:
float x = 1e-30; x /= 1e20; // Underflow!
Computers use only 0 and 1 to represent data so that the range of values that can be represented is limited. Many computers use 32 bits to store integers, so the largest unsigned integer that can be stored in this case is 2^32 -1 = 4294967295. But the first bit is used to represent the sign, so, in fact, the largest value is 2^31 - 1 = 2147483647.
The situation where an integer outside the allowed range requires more bits than can be stored is called an overflow.
Similarly, with real numbers, an exponent that is too small to be stored causes an underflow.
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