OverflowError

The code below won’t compile because of potential overflow, i.e., Unhandled exception: Arithmetic overflow (OverflowError)

class Foo
  def initialize(@w : UInt16, @h : UInt16)
    @bar = Array(UInt32).new(@w * @h, 0)
  end
end

f = Foo.new(640, 480)

What would be the “Crystal way” of ensuring successful compilation of such code?

It should compile perfectly fine, the overflow error occurs at runtime.

But to answer your question, it overflows because @w * @h is still an UInt16 multiplied with an UInt16 and Crystal only casts this value to an UInt32 after the calculation.

You can fix this by casting @w to a UInt32 before multiplying it, like @w.to_u32 * @h.

2 Likes

Perfect. Thanks !

1 Like