Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int32.maxvalue + 1 overflow a long?

Tags:

c#

.net

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 stating "The operation overflows at compile time in checked mode". I know that I could put this in an "unchecked" block and be fine, but my question is why does the error appear in the first place? Clearly a long can hold a int's max value plus one.

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

like image 388
BradleyDotNET Avatar asked Jan 31 '14 19:01

BradleyDotNET


2 Answers

It is because the calculations on the right hand side of assignment is being done in integer type. And it is overflowing integer

You can fix that with:

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

By casting at least one of the operand to long

The reason you get the error is specified in C# specifications.

See C# Specification Section 4.1.5 (Integral types)

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

In your case since both operands of addition can be represented in int therefore the calculation is done in integer type. Explicitly casting one of the operand to long would result in long result and thus no overflow error.

like image 92
Habib Avatar answered Oct 21 '22 16:10

Habib


Your code in fact looks like this:

(long)(int.MaxValue + 1)

But because .Net framework has an inbuilt implicit conversion between int and long you do not have to explicitly put a cast to long in your code.

So firstly this part of the code is executed:

int.MaxValue + 1

and the result of this operation is an int value which causes and overflow exception. So your code does not even have a chance to start the conversion from int to long.

like image 41
Paweł Bejger Avatar answered Oct 21 '22 16:10

Paweł Bejger