Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-1 * int.MinValue == int.MinValue?? Is this a bug?

In C# I see that

-1 * int.MinValue == int.MinValue 

Is this a bug? It really screwed me up when I was trying to implement a search tree. I ended up using (int.MinValue + 1) so that I could properly negate it.

like image 334
James Avatar asked Sep 01 '10 21:09

James


1 Answers

This is not a bug.

int.MinValue * -1 is 1 greater than int.MaxValue can hold. Thus, the number wraps around back to int.MinValue.

This is basically caused by an integer overflow.

Int32.MinValue:

The value of this constant is -2,147,483,648

Int32.MaxValue:

The value of this constant is 2,147,483,647

So, -2,147,483,648 * -1 = 2,147,483,648 which is 1 greater than Int32.MaxValue.

like image 166
jjnguy Avatar answered Oct 05 '22 11:10

jjnguy