How do I able to add Int::MAX + 1
without getting OverflowException
? I know I can do
def add_unsafe(a : Int, b : Int) : Int
((a.to_i128 + b.to_i128) % Int32::MAX).to_i
end
But is there any alternative to do this?
You're looking for wrapping operators. Most math operators have a wrapping variant prefixed with &
. So in your case, that would be a &+ b
.
Btw. your example doesn't work because to_i
still does an overflow check. So calling add_unsafe(Int32::MAX, 1)
raises an error.
A more accurate representation of wrapping behaviour would be (a.to_i128 + b.to_i128) % Int32::MAX
. The &+
operator is obviously better, though.