No overflow error at compile time when int.MaxValue assigned to a variable

Viewed 124

In C#, I understand that the following code will fail because of integer overflow:

int max = int.MaxValue + 1; // error CS0220: The operation overflows at compile time in checked mode

But then, why the following C# code does not fail at compile time and just warp around?

int max = int.MaxValue;
int res = max + 1; // -2147483648
2 Answers

You need to explicitly enabled overflow checking with checked keyword.

The compiler does not do in-depth analysis to detect any possible outcome where an integer variable could overflow. The first example is fairly obvious - the second needs to analyze two different lines of code to detect the overflow, which the compiler is not designed to do.

From the documentation for the checked keyword (emphasis added):

By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow.

Related