Why is int32.maxvalue + 1 overflowing?

If you put the following code in a .NET 4.5 application:

public const long MAXIMUM_RANGE_MAGNITUDE = int.MaxValue + 1; 

A compiler error is generated that says: "The operation overflowed during compilation in verification mode." I know that I could put this in an β€œunverified” block and be fine, but my question is, why does the error appear in the first place? Obviously, long can contain an int max value plus one.

Note that using Int32 and Int64 instead of long and int does not help.

+6
source share
5 answers

This is because the calculations on the right side of the assignment are performed in an integer type. And this overwhelming whole

You can fix this with:

 public const long MAXIMUM_RANGE_MAGNITUDE = int.MaxValue + (long)1; // or 1L 

Throwing at least one of the operands long

The reason you get the error is indicated in the C # specs.

See C # 4.1.5 Specifications Section (Integral Types)

For binary numbers +, -, *, /,%, &, ^, |, == ,! =,>, <,> = and <= operators, operands are converted to type T, where T is the first int, uint, long and ulong , which can fully represent all possible values ​​of both operands. Then the operation is performed using precision of type T, and the result type is T (or bool for relational operators). It is not allowed that one operand is of type long, and the other is of type ulong with binary operators.

In your case, since both operands of addition can be represented in int , therefore, the calculation is performed in an integer type. Explicit casting of one of the operands to long will result in a long result and, therefore, will not lead to an overflow error.

+15
source

Your code actually looks like this:

 (long)(int.MaxValue + 1) 

But since the .NET framework has a built-in implicit conversion between int and long, you do not need to explicitly specify a throw in your code.

So, this piece of code is executed first:

 int.MaxValue + 1 

and the result of this operation is an int value that causes an overflow exception and an exception. Thus, your code does not even have a chance to start converting from int to long.

+4
source

I think this is due to the fact that the value int.MaxValue + 1 computed before the translation in long is performed. Of course, long ones can hold a value, but since you are doing an integer addition, it is not possible to store the integer value int.MaxValue + 1 in int until casting is done.

+1
source

try

 public const long MAXIMUM_RANGE_MAGNITUDE = (long)int.MaxValue + 1L; 
+1
source

Paste the constant value into a long one.

 public const long MAXIMUM_RANGE_MAGNITUDE = (long) int.MaxValue + 1; 
+1
source

All Articles