# Error: variable inside a loop

**URL:** <https://discourse.julialang.org/t/error-variable-inside-a-loop/21504>\
**Category:** General Usage\
**Created:** [March 5, 2019, 7:51pm UTC](https://discourse.julialang.org/t/error-variable-inside-a-loop/21504 "2019-03-05T19:51:48Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![longemen3000](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/longemen3000/32/7298_2.png) [@longemen3000](https://discourse.julialang.org/u/longemen3000)\
**Post date:** [March 5, 2019, 8:03pm UTC](https://discourse.julialang.org/t/error-variable-inside-a-loop/21504/2 "2019-03-05T20:03:33Z")

</div>

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](https://discourse.julialang.org/t/new-scope-solution/16707/55) ). One way is to directly use the variable using the `global` prefix:

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

```

But I recommend using directly the iterator:

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

```

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

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

```

so, you have this

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

```

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

```julia

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
julia> x = myfn!(0)
1
2
3
4
5
julia> x
5

```

---

_[View the full topic](https://discourse.julialang.org/t/error-variable-inside-a-loop/21504)._
