If I have integer variable with maximum value assigned it which is (2,147,483,647)
for 32 bit integer, and if I am incrementing it by 1 then it turn to (-2147483648)
negative value
code
int i = int.MaxValue; // i = 2,147,483,647
i = i + 1;
Response.Write(i); // i = -2,147,483,648
Can anyone explain me? I did not find the exact reason for this change in values.
This is just integer overflow, where the value is effectively leaking into the sign bit. It's simpler to reason about it with sbyte
, for example. Think about the bitwise representations of 127 and -127 as signed bytes:
127: 01111111
-128: 10000000
Basically the addition is performed as if with an infinite range, and then the result is truncated to the appropriate number of bits, and that value "interpreted" according to its type.
Note that this is all if you're executing in an unchecked
context. In a checked
context, an OverflowException
will be thrown instead.
From section 7.8.4 of the C# 5 specification:
In a
checked
context, if the sum is outside the range of the result type, aSystem.OverflowException
is thrown. In anunchecked
context, overflows are not reported and any significant high-order bits outside the range of the result type are discarded.
See more on this question at Stackoverflow