# Global variable disappears

**URL:** https://discourse.julialang.org/t/global-variable-disappears/4021
**Category:** General Usage
**Tags:** scope
**Created:** [May 31, 2017, 7:03pm UTC](https://discourse.julialang.org/t/global-variable-disappears/4021 "2017-05-31T19:03:19Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![ulysses](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ulysses/32/665_2.png) [@ulysses](https://discourse.julialang.org/u/ulysses)
#### Post date: [May 31, 2017, 7:03pm UTC](https://discourse.julialang.org/t/global-variable-disappears/4021/1 "2017-05-31T19:03:19Z")

</div>

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

```julia
// 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:

```julia
// 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?

---

<div class="post-metadata">

### Author: ![ExpandingMan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/expandingman/32/866_2.png) [@ExpandingMan](https://discourse.julialang.org/u/ExpandingMan)
#### Post date: [May 31, 2017, 7:08pm UTC](https://discourse.julialang.org/t/global-variable-disappears/4021/2 "2017-05-31T19:08:54Z")

</div>

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

---

<div class="post-metadata">

### Author: ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)
#### Post date: [May 31, 2017, 7:09pm UTC](https://discourse.julialang.org/t/global-variable-disappears/4021/3 "2017-05-31T19:09:02Z")

</div>

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
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

```
