'.NET / C# - Allow overflowing of integers
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)
Solution 1:[1]
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) ...
Solution 2:[2]
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)
Solution 3:[3]
Throw it into an unchecked block: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unchecked
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kevin Montrose |
| Solution 2 | nitzmahone |
| Solution 3 | Janus |
| Solution 4 | Pranay Shirolkar |
