I know, Int32.MaxValue * Int32.MaxValue
will yield a number larger than Int32
; But, shouldn't this statement raise some kind of an exception?
I ran across this when doing something like IF (X * Y > Z)
where all are Int32
. X
and Y
are sufficiently large enough, you get a bogus value from X * Y
.
Why is this so and how to get around this? besides casting everything to Int64
.
Because int32 confines the results to 32bits.
So, if you have a look at the math at a byte level.
FFFFFFFF * FFFFFFFF = FFFFFFFE00000001
As you can see, the lowest 4 bytes = 1.
By default, C# arithmetic is done in an unchecked context, meaning values will roll over.
You can use the checked and unchecked keywords to control that behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With