Artur Keyan
Artur Keyan

Reputation: 7683

-1 * int.MinValue gives an error

When I write this code

Console.WriteLine(-1 * int.MinValue);

or

int a = -1 * -2147483648;

I get an error

The operation overflows at compile time in checked mode.

Is there compile time check especially for this value? or is it counting all written expressions real time?

Upvotes: 1

Views: 254

Answers (4)

OSH
OSH

Reputation: 2937

There are run time checks for values. int values are from -21474048 to +21474047 (why? 2's complement). So you get an exception.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502286

There's no need for this to be a special check - the value naturally overflows. It's just like:

Console.WriteLine(int.MaxValue + 1);

That clearly overflows int - and it's the same value as int.MinValue * -1.

From section 7.19 of the C# 4 spec:

Unless a constant expression is explicitly placed in an unchecked context, overflows that occur in integral-type arithmetic operations and conversions during the compile-time evaluation of the expression always cause compile-time errors.

Upvotes: 3

Rune Grimstad
Rune Grimstad

Reputation: 36330

The Int (or rather Int32) can hold any 32 bit integer value. It ranges from -2147483648 to 2147483647.

-1 * -2147483648 = 2147483648. And that is greater than the max Int32 value. That is the reason you get an overflow.

If you want to do the calculation you can cast one of the values to an Int64. So this should work:

(Int64)(-1)*int.MinValue;

Upvotes: 3

mjwills
mjwills

Reputation: 23975

The compiler is able to perform the (multiplication) calculation at compile time rather than runtime, so it does.

Since -1 * int.MinValue (-1 * -2,147,483,648, thus 2,147,483,648) is greater than int.MaxValue (2,147,483,647) it gives you your compile error.

To prove that it isn't special casing your exact statement, try:

Console.WriteLine(-2 * 1073741826);

and you will get the same behaviour.

Upvotes: 9

Related Questions