Search code examples
scopeglobal-variablesjulia

Does scoping in julia 1.0.0 with for-loops make sense to beginners?


In julia 1.0.0, I get the following for-loop scoping behavior:

julia> counts = 0
0
julia> for i in 1:10
       counts += 1
   end
ERROR: UndefVarError: counts not defined

I found the solution was to make the counts variable global inside the for loop.

julia> for i in 1:10
           global counts += 1
       end
julia> counts
10

However, as a newcomer to julia this behavior almost made me quit the language because it seems so different from other languages.

Now that I see the solution above, I wonder if this is intuitive to beginning julia users. It was not intuitive to me, though I was finally able to solve it after quite a bit of time.

Here is the confusing part. I thought making a variable global when it was initialized would solve the problem. It does not:

julia> global c = 0
julia> for i in 1:10
           c += 1
       end
ERROR: UndefVarError: c not defined

It would seem natural that the global scope of c above would flow down into the for-loop, but the first initialization of c in the for-loop apparently creates a different for-loop local c.

Does this make sense to experienced julia developers?


Solution

  • I think there is agreement that, for interactive usage, this behavior is not optimal and it is likely going to change to the expected behavior in the REPL, IJulia etcetera soon. You can find the discussion here: https://github.com/JuliaLang/julia/issues/28789

    Note, however, that everything works as expected once you wrap it into a local scope, such as a function or a let block for example.

    See my answer here: Scope of variables in Julia for some more information/references.