Is it a bug or I am doing something wrong?

I am going through Julia Documentation and in overflow section i get weird result,

julia> typemax(Int16)
32767

julia> x=typemax(Int16)
32767

julia> x+1
327671

julia> x + 1
327671
julia> 

EDIT:
I restart my REPL and it works

1 Like
julia> i = typemax(Int16)
32767

julia> j = i + 1
32768

julia> typeof(j)
Int64
3 Likes
julia> typemax(Int16) + 1
32768

I think you need to restart your Julia session. You may have overwritten some methods somewhere.

3 Likes

It works fine for me, note when you add 1 to the Int16 maximum, x automatically becomes Int64
image

1 Like

To add to @Paul_Warburton’s reply, as this behaviour might be somewhat confusing for newcomers, the reason is that 1 is an Int64 (well, at least on 64-bit Julia).

julia> typeof(1)
Int64

In the addition our Int16 typemax will then get promoted to Int64, resulting in a sum of type Int64.

If you want to actually get an Int16 overflow, you’ll need the Int16 (or lower precision) version of 1, e.g. via one(Int16) or Int16(1).

julia> typemax(Int16) + one(Int16)
-32768
9 Likes

For those wanting (one way) to replicate the OP’s results:

julia> x + y = parse(Int, string(x, y))
+ (generic function with 1 method)

julia> typemax(Int16)
32767

julia> typemax(Int16) + 1
327671

:wink:
(See this response and the post in general for more fun details: A most harrowing collection of Julia WATs - #10 by Philogicatician)

1 Like