Redefining constants in functions, confusing behavior

Hello all,

I know that redefining constants is discouraged and is only allowed as a convenience. However, I found this confusing:

julia> const x1=0;const x2=0;

julia> function f1()
       global x1+=1
       i->i+x1
       end
f1 (generic function with 1 method)

julia> function f2()
       i->(global x2+=1;i+x2)
       end
f2 (generic function with 1 method)

julia> f1()(0),f2()(0)
WARNING: redefining constant x1
WARNING: redefining constant x2
(1, 0)

julia> const x1=0;const x2=0;

julia> function f1()
       global x1+=1
       i->i+x1
       end
f1 (generic function with 1 method)

julia> function f2()
       i->(global x2+=1;i+x2)
       end
f2 (generic function with 1 method)

julia> f1()(0),f2()(0)
WARNING: redefining constant x1
WARNING: redefining constant x2
(1, 0)

julia> x1,x2
(1, 1)

Can someone please help me understand why the behavior of the two functions is different, or whether/why it is expected.

Cheers!

The whole reason it is discouraged is because the resulting behavior is potentially confusing and you can’t really expect anything.

2 Likes

This is undefined behavior so any results is reasonable. The exact reason is simply whatever the compiler want to respect your assignment or assume and the behavior is not guaranteed to be stable.

1 Like

I was fishing for insight, but I take both your words for it, there may be none. Undefined behavior is a perfectly acceptable answer to me, I would mark both replies as solutions if i could, thanks :slight_smile: