I am trying to prevent overflow in two situations, one is when multipling a long with a float, and the other is when adding two longs.
Like:
public static long multiplyLong(long value, float multiplier)
{
if (value * multiplier > long.MaxValue)
{
Debug.Log("greater then max value");
return value = long.MaxValue;
}
else
{
Debug.Log("not greater then max value");
return (long) (value * multiplier);
}
}
public static long addLong(long value, long adder)
{
if(value + adder > long.MaxValue)
{
Debug.Log("greater then max value");
return value = long.MaxValue;
}
else
{
Debug.Log("not greater then max value");
return value + adder;
}
}
"multiplyLong" works perfectly, while "addLong" doesn't work like it should. When using addLong, and there will be a overflow it doesn't detect the overflow. I think this is weird because the code seems okay.
Can someone help me?
"checked" isn't an option btw.
Like @Bradley said, you are getting an overflow in your check for overflows. But the problem is bigger than that.
Lets look at this line first
Here, both
value
andadder
are longs, and adding them together will result in a long. But the problem is that longs automatically roll over instead of throwing exceptions, so if your values are larger than the max value for long, you will just get some other long value seemingly at random.Now it should be clear why you don't want to do this but before we get into what the correct solution is, lets look at your
multiplyLong
method. Specifically, the following lineIn this
value
is a long, andmultiplier
is a float, and multiplying them together results in a float, which can easily be checked against a long so your check is going to appear to work.But what if the value of
value * multiplier
is greater thanlong.MaxValue
and cast it as along
?the answer is that you get
long.MinValue
, which is certainly less thanlong.MaxValue
There is much more that can be said on this topic but, this should be enough to convince you that what you are doing is not great.
Now, what should you do? I recommend using the
decimal
type for two reasons. One, it has a much larger range thanlong
(decimal
can go up to79228162514264337593543950335
, wherelong
can only go up to9223372036854775807
), the other reason is that it throws explicit exceptions when overflows happen.For example, here is my rewritten version of your code