Actually the local
there is somewhat redundant:
function tst()
a = 0
# or this, if you do not need any specific initial value for a
# local a
for i in 1:10
b = 2
a = 3 + b
end
print("a= ", a)
end
tst()
julia> tst()
a= 5
Probably we should add that using local b
inside the loop allows one to use the name b
for a variable inside the loop which repeats the name of a variable in the outer scope:
julia> function tst()
a = 0 ; b = 1
for i in 1:10
local b = 2
a = 3 + b
end
print("a=",a," b=",b)
end
tst (generic function with 1 method)
julia> tst()
a=5 b=1 # b is not changed in the loop
Although we should never do that, as the code might become a mess.
I think (not completely sure) that the fact that b
is local to the scope of the loop allows for possible compiler optimizations which would not be possible otherwise. For instance, in my experience, some codes like this in Julia run faster than the almost equivalent translations of Fortran codes, and I this might be one of the explanations, because in Fortran you do not have that exclusive scope for variables in loops.