1

I'm trying to understand the scope rules in Julia. I've tried a for loop with z as a regular integer variable:

z = 2
for i = 1:4
    z += 1
end
println(z)

and it gives me an UndefVarError: z not defined error, unless I put global z inside of the loop.

However, if I make z a 1x1 array it works perfectly fine without global:

z = [2]
for i = 1:4
    z .+= 1
end
println(z)
$ julia test.jl
  [6]

What's the difference between scopes of arrays and variables?

1 Answer 1

1

The contents of an array assigned to a global variable are constant in type:

julia> a = [1]
1-element Array{Int64,1}:
 1

julia> push!(a, "s")
ERROR: MethodError: Cannot `convert` an object of type String to an 
    object of type Int64

And const typed globals are OK to be referenced within loops.

Sign up to request clarification or add additional context in comments.

6 Comments

If that were the case, I would think that const x = 0; for i in 1:4; x +=1 end would work, but it doesn't.
Once you call a scalar number like x a const you cannot change the value of x: 0 is always 0. But a vector's contents can be changed in Julia without changing the vector's reference and type.
Well, technically you can change the value of a constant scalar. Try const x = 0; x = 1. It just prints a warning.
Ok, I think the key point is in the second sentence of your comment. To paraphrase, a global variable can be changed in a for loop as long as the variable's type and memory reference don't change. This is what the manual means when it says that "in a local scope, all variables are inherited from its parent global scope block unless ... an assignment would result in a modified global variable...". Thus "modified" boils down to the memory reference changing, which happens when you change the value of a constant scalar, but doesn't happen when you change the values of elements in an array.
Oh, yes true Cameron, you can change the value of a const with just a warning, but not its type (try it!). The issue is potential type changes of global variables after the compiler has made type assumptions about the variable. The array can be mutated without violating the JIT compiler's assumptions about the data's reference in memory.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.