In an unchecked context, is adding one to an integer with the value 2147483647
guaranteed to result in -2147483648
?
For example, with the following code
const int first = int.MaxValue;
int second = first;
if ( second >= first )
{
Console.WriteLine( "First check" );
}
second++;
if ( second >= first )
{
Console.WriteLine( "Second check" );
}
In C++, it would be perfectly valid for both "First check" and "Second check" to be printed, as the optimizer can reuse the result of the first check for the second.
Is the same true of C#?
From the spec:
4.1.5 Integral Types
The checked and unchecked operators and statements are used to control overflow checking for integral-type arithmetic operations and conversions (§7.6.12). In a checked context, an overflow produces a compile-time error or causes a System.OverflowException to be thrown. In an unchecked context, overflows are ignored and any high-order bits that do not fit in the destination type are discarded.
That is the only description of the behavior that I could find, but it seems sufficient. So yes, adding one to Int32.MaxValue
will result in the value Int32.MinValue
using two's complement representation.
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