# Another undefined variable puzzle

**URL:** <https://discourse.julialang.org/t/another-undefined-variable-puzzle/132025>\
**Category:** General Usage\
**Tags:** question\
**Created:** [September 1, 2025, 4:18pm UTC](https://discourse.julialang.org/t/another-undefined-variable-puzzle/132025 "2025-09-01T16:18:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/alan/32/15970_2.png) [@alan](https://discourse.julialang.org/u/alan)\
**Post date:** [September 1, 2025, 4:18pm UTC](https://discourse.julialang.org/t/another-undefined-variable-puzzle/132025/1 "2025-09-01T16:18:02Z")

</div>

Here is some code that (I think) ought to work, but doesn’t:

```julia-auto
module foo

x = 1 # line 3
while true
    y = x # line 5
    x = 4 # line 6
    break
end

end # module

```

The error message (below) says that x on line 5.is undefined in local scope. This message goes away if I remove line 6. With or without line 6, the assignment on line 3 ought to prevent this problem. What am I missing?

```julia-auto
julia> include("foo.jl")
ERROR: LoadError: UndefVarError: `x` not defined in local scope
Suggestion: check for an assignment to a local variable that shadows a global of the same name.
Stacktrace:
 [1] top-level scope
   @ ~/txt/mapmix/julia/MapMix/test/foo.jl:5
 [2] include(fname::String)
   @ Main ./sysimg.jl:38
 [3] top-level scope
   @ REPL[2]:1
in expression starting at /Users/rogers/txt/mapmix/julia/MapMix/test/foo.jl:1

```

---

<div class="post-metadata">

**Author:** ![franckgaga](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/franckgaga/32/218241_2.png) [@franckgaga](https://discourse.julialang.org/u/franckgaga)\
**Post date:** [September 1, 2025, 4:47pm UTC](https://discourse.julialang.org/t/another-undefined-variable-puzzle/132025/2 "2025-09-01T16:47:42Z")

</div>

You need to specify explicitly that you want to access the global variable `x`:

```julia
module foo

x = 1        
while true
    global x # newline !!!
    y = x    
    x = 4    
    break
end

end # module

```

We all agree that is not easy to remember, but there is a good reason for this: to discourage the use of (non-`const`) global variables, since they are dangerous for the performances and involuntary overwriting. Details here (but this part of the manual is hard to read, IMO): [Scope of Variables · The Julia Language](https://docs.julialang.org/en/v1/manual/variables-and-scoping/#scope-of-variables)

I don’t know what you are trying to do exactly, but a good approach here would be to incorporate the code in a function, since `x` is no longer a global variable:

```julia
module foo

function func()
    x = 1 # line 3
    while true
        y = x # line 5
        x = 4 # line 6
        break
    end
    return nothing
end

end # module

```
