Why const changes the behavior of Ptr?

In the docs:

julia> const s1 = "1"
"1"

julia> s2 = "1"
"1"

julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
 Ptr{UInt8} @0x00000000132c9638
 Ptr{UInt8} @0x0000000013dd3d18

julia> s1 = s2
"1"

julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
 Ptr{UInt8} @0x0000000013dd3d18
 Ptr{UInt8} @0x0000000013dd3d18

but on my machine (wsl2-ubuntu20.04LTS on win10 with julia 1.5.3):

julia> const s1 = "1"
"1"

julia> s2 = "1"
"1"

julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
 Ptr{UInt8} @0x00007feda50dbc58
 Ptr{UInt8} @0x00007feda50f1b98

julia> s1 = s2
"1"

julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
 Ptr{UInt8} @0x00007feda50dbc58
 Ptr{UInt8} @0x00007feda50f1b98

After s1 = s2, the pointers of s1 and s2 are not the same, which is inconsistent with the example in the documentation. Why?

When I do not use const:

julia> s1 = "1"
"1"

julia> s2 = "1"
"1"

julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
 Ptr{UInt8} @0x00007f9a8e891318
 Ptr{UInt8} @0x00007f9a8e8a4018

julia> s1 = s2
"1"

julia> pointer.([s1, s2], 1)
2-element Array{Ptr{UInt8},1}:
 Ptr{UInt8} @0x00007f9a8e8a4018
 Ptr{UInt8} @0x00007f9a8e8a4018

Edit: First of all: Hi there, welcome to the Julia community!

Because you ask it to redefine a constrant, which is a bad thing to do, so Julia doesn’t really want to. It therefore checks if you really did redefine it or merely assigned an equal thing, which you did. It just ignored your assignment.

julia> const z = "hi"
"hi"

julia> z = "hi"
"hi"

julia> z = "there"
WARNING: redefinition of constant z. This may fail, cause incorrect answers, or produce other errors.
"there"

So if you take 2 non-equal value for s1 and s2 you get the expected behaviour together with an appropriate warning:

julia> const s1 = "1"
"1"

julia> s2 = "2"
"2"

julia> pointer.([s1,s2],1)
2-element Vector{Ptr{UInt8}}:
 Ptr{UInt8} @0x0000000019c00e98
 Ptr{UInt8} @0x0000000019cbdfb8

julia> s1 = s2
WARNING: redefinition of constant s1. This may fail, cause incorrect answers, or produce other errors.
"2"

julia> pointer.([s1,s2],1)
2-element Vector{Ptr{UInt8}}:
 Ptr{UInt8} @0x0000000019cbdfb8
 Ptr{UInt8} @0x0000000019cbdfb8

Is this in the most recent docs?

2 Likes

Thank you!
I did not find your description in Constants(it says “if an assignment would not result in the change of variable value no message is given”), maybe I missed it or it is somewhere else.