Global variable disappears

I have the following scenario for initialization of a global variable which fails for some mysterious reason.

// t.jl
n = 1
function f()
    if n == 1
        n = 2
    end
    println(n)
end
...
julia> include("t.jl")
f (generic function with 1 method)

julia> f()
ERROR: UndefVarError: n not defined
Stacktrace:
 [1] f() at t.jl:3

While it is perfectly clear to, e.g., just print a global variable:

// t.jl
n = 1
function f()
    println(n)
end
...
julia> include("t.jl")
f (generic function with 1 method)

julia> f()
1

Can anyone explain the reason which causes global variable disappear? What are the limitations on using global variables?

In order to assign global variables from a function one must use the keyword global.

1 Like

A variable is either global or local within a given scope, never both. By having an assignment n = 2 inside your first function, Julia treats n as a new local variable everywhere inside the function, and that variable is undefined until the n = 2 line.

If you want to set a global variable, you need to explicitly mark it as global to prevent this from happening:

julia> n = 1
1

julia> function f()
         global n
         if n == 1
           n = 2
         end
         println(n)
       end
f (generic function with 1 method)

julia> f()
2

julia> n
2
2 Likes