# Error: variable inside a loop

I do not understand why it’s an error:

``````x = 0
while x < 5
x += 1
println(x)
end
``````

I am using Julia 1.1.0 on Windows. This is the error msg:

``````ERROR: UndefVarError: x not defined
Stacktrace:
 top-level scope at .\REPL:2 [inlined]
 top-level scope at .\none:0
``````

Similar result using for loop:

``````x = 0
for i = 1:5
x += 1
println(x)
end
``````
2 Likes

For what i understand (and is not a lot), there is a problem with the scope of the function, as the variables inside the loop can’t access variables outside the loop (for more information, you can read this discourse thread New Scope Solution ). One way is to directly use the variable using the `global` prefix:

``````x = 0
for i = 1:5
global x += 1
println(x)
end
``````

But I recommend using directly the iterator:

``````for i = 1:5
println(i)
end
``````

If you really need to use that `x`, you can make a function:

``````function myfn(x)
for i=1:5
println(x+i)
end
end

``````

so, you have this

``````julia> myfn(2)
3
4
5
6
7
``````

if you want the x modified, you can do something like this

``````
function myfn!(x)
#in julia, the ! means that the function modifies the argument, generally the first one
for i=1:4 # the return statement prints x
x+=1
println(x)
end
return x
end
``````
``````julia> x = myfn!(0)
1
2
3
4
5
julia> x
5
``````
2 Likes

For now, I think the easiest thing to do is either (1) stick in Jupyter for these sorts of interactive code, and (2) wrap anything that involves for or while loops in functions (e.g.

``````function f()
x = 0
while x < 5
x += 1
println(x)
end
end
f()
``````
4 Likes

It’s worth noting that `let` will also work just as well:

``````let x = 0
while x < 5
x += 1
end
println(x)
end
``````
4 Likes

Encounterd similar behaviour, this is very unintuitive - own scope in `for` loop. Should be writing in big font in docs about this or through an instructive exception.

2 Likes

This worked perfectly fine for me.

One rather important distinction between the previous while loop form and the for loop form is the scope during which the variable is visible. If the variable i has not been introduced in another scope, in the for loop form, it is visible only inside of the for loop, and not outside/afterwards.

From the Repeated Evaluation: Loops section of the manual. There is also a nice table at the start of the next section Scope of Variables that includes the loop constructs.

I think I have not understood what you said, because every language I know creates a new scope inside a `for` construct.