views:

67

answers:

2

Hello,

Recently i started making a item container, and every time the user tries to add an item into the container. If somehow the same item type exists, it'll stack them on top of each other, but there's a limit, which is int.MaxValue and if i tried:

if (2147483647 + 2147483647 > int.MaxValue)

That would give me the following error:

The operation overflows at compile time in checked mode

So i tried to use the unchecked keyword like so:

unchecked
{
     if (2147483647 + 2147483647 > int.MaxValue)
     {
     }
}

but this doesn't show trigger the if statement at all (I'm guessing it's wrapped around a Logical AND operator?)

Is there other ways to do this? (without using something like a int64, etc)

+1  A: 

Try casting both to uint (unsigned) if you don't need the negative half of the bitspace. Same bit width, just doesn't roll negative after Int.MaxValue (eg, it's 2x the magnitude of int.MaxValue)

nitzmahone
+2  A: 

If an int operation overflows its not going to test greater than Int32.MaxValue.

If you want that condition to be true, use longs.

if (2147483647L + 2147483647L > int.MaxValue) ...

Alternatively, use uints.

if (2147483647U + 2147483647U > (uint)int.MaxValue) ...
Kevin Montrose
or you could note, as the compiler no doubt will, that the condition is always true.
GregS