void main () {
int i;
if (i < 0) { i = -i; };
}
Can anyone help me to understand why an overflow may occur in the above program?
An integer overflow or wraparound happens when an attempt is made to store a value that is too large for an integer type. The range of values that can be stored in an integer type is better represented as a circular number line that wraps around.
An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128).
An 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.
An overflow may occur because the range of integer representation in two's complement is not symmetric: the magnitude of the smallest negative number that can be represented is the magnitude of the highest positive number that can be represented, plus one. For example, on a 32-bit system the values are -2,147,483,648
and 2,147,483,647
. That's why negating -2,147,483,648
would result in an overflow: the result of negation, a positive value 2,147,483,648
, cannot be represented in an int
of the same size.
Note that the inverse of this problem is not true: negating a positive number would not result in an overflow:
if (i > 0) { i = -i; } // No overflow here
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