From Int64 to Int128

Hi there,
I (as a noob) have a basic question:

x = typemax(Int32)
x = x + 1
typeof(x) 

i get Int64. So we go from Int32 to Int64

y = typemax(Int64)
y = y + 1

y now is -9223372036854775808

Why we cannot go to Int128? Does this depend on the system architecture?

Thx

It’s much simpler than this. 1 is an int64 (on 64 bit machines). Thus, when you add an int32 to an int64, you get an int64.

6 Likes

Indeed

julia> typemax(Int32) + Int32(1)
-2147483648

and conversely,

julia> typemax(Int64) + Int128(1)
9223372036854775808

Julia does not and will not do automatic widening of Int because that has gigantic, negative performance implications.

4 Likes

Ouch… yes, ok

Thx a lot.

2 Likes

One thing you can do is use a pacakge like SaferIntegers.jl

julia> using SaferIntegers

julia> @saferintegers begin
           typemax(Int) + 1
       end
ERROR: OverflowError: 9223372036854775807 + 1 overflowed for type Int64
Stacktrace:
 [1] throw_overflowerr_binaryop(::Symbol, ::Int64, ::Int64) at ./checked.jl:154
 [2] checked_add at ./checked.jl:166 [inlined]
 [3] + at /home/mason/.julia/packages/SaferIntegers/lLDKG/src/arith_ops.jl:21 [inlined]
 [4] +(::Int64, ::SafeInt64) at /home/mason/.julia/packages/SaferIntegers/lLDKG/src/arith_ops.jl:71
 [5] top-level scope at REPL[31]:2

This way, these things are explicitly caught and you can use more appropriate number types.

4 Likes

Amazing… thank you too