Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C#/.NET signed integer overflow behavior defined?

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#?

like image 482
Matt Avatar asked Oct 06 '14 21:10

Matt


1 Answers

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.

like image 116
Ed S. Avatar answered Sep 21 '22 22:09

Ed S.