Why isn't an overflow exception raised?

The following runs fine without error and diff is 1:

int max = int.MaxValue;
int min = int.MinValue;
//Console.WriteLine("Min is {0} and max is {1}", min, max);
int diff = min - max;
Console.WriteLine(diff);

Wouldn't then all programs be suspect? a+b is no more the sum of a and b, where a and b are of type int. Sometimes it is, but sometimes it is the sum* of a, b and 2*int.MinValue.

* Sum as in the ordinary English meaning of addition, ignoring any computer knowledge or word size

In PowerShell, it looks better, but it still is not a hardware exception from the add operation. It appears to use a long before casting back to an int:

[int]$x = [int]::minvalue - [int]::maxvalue
Cannot convert value "-4294967295" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
Jon Skeet
people
quotationmark

By default, overflow checking is turned off in C#. Values simply "wrap round" in the common way.

If you compiled the same code with /checked or used a checked { ... } block, it would throw an exception.

Depending on what you're doing, you may want checking or explicitly not want it. For example, in Noda Time we have overflow checking turned on by default, but explicitly turn it off for GetHashCode computations (where we expect overflow and have no problem with it) and computations which we know won't overflow, and where we don't want the (very slight) performance penalty of overflow checking.

See the checked and unchecked pages in the C# reference, or section 7.6.12 of the C# language specification, for more details.

people

See more on this question at Stackoverflow