Search code examples
juliaglobal-variables

global scope in Julia


I have a piece of code in Julia here:

i = 1
while true
    if i == 10
        break
    end
    
    global i += 1 #A
    
    for k = 1:1
        println(i) #B
    end
end
println(i)

My question is why global i += 1 #A is required inside while loop, but println(i) #B inside the for loop is not requiring any global declaration?

Is global declaration required only for the modification of variables? The if i == 10 statement after the while declaration is using the global scope.


Solution

  • In Julia, loop bodies introduce local scopes the same as function bodies. If you assign to a variable that isn’t already a local or explicitly declared to be global, then it is, by default, a new local variable. Combining those two facts implies that assigning to i inside of the loop causes it to be a new local. On the other hand, if you don’t assign to it and only access it then it must be a variable from some outer scope, local or global, but in this case global.

    Regarding the second question: a variable in a given scope can only have one meaning—it’s either local or global. It can’t be local in one part of the loop body and global in a different part (unless there’s an inner nested scope, but then that’s a different scope region). If it’s declared global anywhere, it’s global everywhere both before and after that declaration. If it’s local then it’s local everywhere.