# Variable not defined when incrementing its value in julia

**URL:** <https://discourse.julialang.org/t/variable-not-defined-when-incrementing-its-value-in-julia/23690>\
**Category:** New to Julia\
**Tags:** question, scope\
**Created:** [April 30, 2019, 8:08am UTC](https://discourse.julialang.org/t/variable-not-defined-when-incrementing-its-value-in-julia/23690 "2019-04-30T08:08:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Luigi\_Marongiu](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/luigi_marongiu/32/7909_2.png) [@Luigi\_Marongiu](https://discourse.julialang.org/u/Luigi_Marongiu)\
**Post date:** [April 30, 2019, 8:08am UTC](https://discourse.julialang.org/t/variable-not-defined-when-incrementing-its-value-in-julia/23690/1 "2019-04-30T08:08:54Z")

</div>

Dear all,  
I am trying to increment the value of a variable with this loop:

```julia
julia> p=0
0
julia> for i in 1:10
       p += 1
       end
ERROR: UndefVarError: p not defined
Stacktrace:
 [1] top-level scope at ./none:2

```

I also tried with:

```julia
julia> p=Int8
Int8
julia> for i in 1:10
       p += 1
       end
ERROR: UndefVarError: p not defined
Stacktrace:
 [1] top-level scope at ./none:2

```

Isn’t `+=` the increment operator? Even if I declare the variable as global (which I think is an overkill) the error persists:

```julia
julia> global p=0
0
julia> for i in 1:10
       p += 1
       end
ERROR: UndefVarError: p not defined
Stacktrace:
 [1] top-level scope at ./none:2

```

What am I getting wrong? Thank you.

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [April 30, 2019, 8:13am UTC](https://discourse.julialang.org/t/variable-not-defined-when-incrementing-its-value-in-julia/23690/2 "2019-04-30T08:13:08Z")

</div>

You need to use `global` in the local scope where you want to access the global variable `p`:

```julia
julia> p = 0
0

julia> for i in 1:10
           global p += 1
       end

julia> p
10

```

---

<div class="post-metadata">

**Author:** ![Luigi\_Marongiu](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/luigi_marongiu/32/7909_2.png) [@Luigi\_Marongiu](https://discourse.julialang.org/u/Luigi_Marongiu)\
**Post date:** [April 30, 2019, 8:21am UTC](https://discourse.julialang.org/t/variable-not-defined-when-incrementing-its-value-in-julia/23690/3 "2019-04-30T08:21:34Z")

</div>

Yes you are right: global goes inside the loop. I have been trying this right now:

```julia
p = 0.0
for j in 1:10
    global p += 1
end
println(p) # 10.0
for i in 1:10
    global p -= 1
end
println(p) # 0.0 (the same variable has been depleted as expected)
p = -1.0 # new assignment
for i in 1:10
    global p -= 1
end
println(p) # -11.0 as expected

```
