Reputation: 355
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.
Upvotes: 0
Views: 400
Reputation: 269
in signed int, first bit shows the sign and the rests shows the number:
so, in 32bit int, first bit is the sign, so maxInt is: 2147483647
or 01111111111111111111111111111111
,
and if we increment this number by 1 it will become: 10000000000000000000000000000000 which is - 2147483647
Upvotes: 1
Reputation: 1502246
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.
Upvotes: 8