开发者

.NET / C# - Allow overflowing of integers

开发者 https://www.devze.com 2022-12-15 14:58 出处:网络
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 开发者_JS

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 开发者_JS百科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)


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) ...


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)


Throw it into an unchecked block: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unchecked


The main reason your if condition isn't getting is because the addition of 2147483647 + 2147483647 will result in -2 because of overflows of int in the unchecked block.

This is the reason your if condition 2147483647 + 2147483647 > int.MaxValue is never going to be true because it'll get evaluated to -2 > int.MaxValue, which isn't true.

0

精彩评论

暂无评论...
验证码 换一张
取 消