# Problem in variable definition in loop

**URL:** <https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752>\
**Category:** New to Julia\
**Created:** [January 17, 2019, 6:04pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752 "2019-01-17T18:04:07Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 17, 2019, 6:04pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/1 "2019-01-17T18:04:07Z")

</div>

Dear all,

I don’t understand this behaviour. How come “j” is not defined in the second round  
of the loop if it was defined on the first?

```julia
julia> for i in 1:2
         if i == 1
           j = 1
         end
         println("i = ", i) 
         println("j = ", j)
       end
i = 1
j = 1
i = 2
ERROR: UndefVarError: j not defined

```

---

<div class="post-metadata">

**Author:** ![alejandromerchan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/alejandromerchan/32/10500_2.png) [@alejandromerchan](https://discourse.julialang.org/u/alejandromerchan)\
**Post date:** [January 17, 2019, 6:31pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/2 "2019-01-17T18:31:58Z")

</div>

Because j never gets defined when i = 2 and it doesn’t exist outside of the loop either. The first time the loop runs j is created inside of the loop, but not in the global environment.

This works as expected

```julia
for i in 1:2
                if i == 1
                  global j = 1
                end
                println("i = ", i) 
                println("j = ", j)
              end
i = 1
j = 1
i = 2
j = 1

```

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 17, 2019, 6:50pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/3 "2019-01-17T18:50:34Z")

</div>

Ok, lets be more specific, because this behaviour seems very strange to me. I want to define some vectors in the first iteration of my loop, because there is were I find out the size they must have. A minimal example would be:

```julia
for i in 1:2
  if i == 1
    n = 2 # Actually this is reading problem data.
    x = zeros(n)
  end
  println("i = ", i) 
  println("x[1] = ", x[1])
end

```

declaring `x` as global does not seem reasonable to me, and this loop is thought to be inside a function, I do not want `x` to be a global variable at all.

In fortran this would be something like:

```julia
double precision, allocatable :: x(:) 
do i = 1, 2
  if i == 1 then
    n = 2
    allocate(x(2))
  end if
  write(*,*) i, x(1)
end do

```

That the definition does not work with a a scalar is disturbing to me, really:

```julia
do i = 1, 2
  if i == 1 then
    j = 2
  end if
  write(*,*) i, j
end do

```

That this code results in an error is very, very disturbing to me.

---

<div class="post-metadata">

**Author:** ![dpsanders](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dpsanders/32/3573_2.png) [@dpsanders](https://discourse.julialang.org/u/dpsanders)\
**Post date:** [January 17, 2019, 7:27pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/4 "2019-01-17T19:27:27Z")

</div>

What happens if you actually wrap all of this in a function? You may also need to define x at the start of the function.

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 17, 2019, 7:31pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/5 "2019-01-17T19:31:52Z")

</div>

Exactly, I need to define x at the start of the function.

That makes things completely equivalent to Fortran, in which I need to declare the variables.

For a vector, I think I could use `x = Vector{}` instead of `allocatable(x)`, but for a scalar it seems I have to define its value:

```julia
julia> function test()
       j = 0
       x = Vector{}
       for i in 1:2
         if i == 1
           j = 1
           x = zeros(3)
         end
         println("i = ", i)
         println("j = ", j)
         println("x = ", x)
         end
       end
      end ; test()

```

This works as expected, although it seems to me that having to define an actual value for the scalar `j` is not ideal. Also, I am not sure if `x = Vector{}` is the best way to go there.

Thanks.

---

<div class="post-metadata">

**Author:** ![septc](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/septc/32/2980_2.png) [@septc](https://discourse.julialang.org/u/septc)\
**Post date:** [January 17, 2019, 7:41pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/6 "2019-01-17T19:41:16Z")

</div>

How about using `local`? For example…

```julia
function test()
    local j, x
    for i in 1:2
        if i == 1
            j = 1
            x = zeros(3)
        end
        println("i = ", i)
        println("j = ", j)
        println("x = ", x)
    end
 end

```

---

<div class="post-metadata">

**Author:** ![jlperla](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlperla/32/34332_2.png) [@jlperla](https://discourse.julialang.org/u/jlperla)\
**Post date:** [January 17, 2019, 7:47pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/7 "2019-01-17T19:47:30Z")

</div>

Try it in a Jupyter notebook. Does the code behave then behave in the way you would expect?

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 17, 2019, 8:03pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/8 "2019-01-17T20:03:52Z")

</div>

Wrapping the code inside a function (which I always do because of the scoping rules of the repl), the two following solutions seem reasonable:

1. Assigning a value to the variable outside the loop

```julia
function test()
  #x = Vector{} (commented to remove this error, pointed out by the next post)
  x = 0.
  j = 0
  for i in 1:2
    if i == 1
      x = rand(3)
      j = 1
    end
    println("i = ", i) 
    println("x = ", x, " j = ", j)
  end
end

```

1. Or declaring a local:

```julia
function test()
  local x
  local j
  for i in 1:2
    if i == 1
      x = rand(3)
      j = 1
    end
    println("i = ", i) 
    println("x = ", x, " j = ", j)
  end
end

```

Seems that the second option provides more information for the compiler, is that correct?

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [January 17, 2019, 8:28pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/9 "2019-01-17T20:28:39Z")

</div>

Just issuing

```julia
local j, x

```

works.

This, however, is wrong:

```julia
x = Vector{}

```

Here you are _not_ declaring the type of the variable, instead you are assigning a type as the _value_ of `x`:

```julia
julia> x = Vector{}
Array{T,1} where T

julia> typeof(x)
UnionAll

```

You could, if you like, add a type, like this:

```julia
local x::Vector{Float64} # note ::, not =. Also Vector{} is the wrong type

```

but I don’t think the type annotation makes any difference.

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 17, 2019, 9:17pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/10 "2019-01-17T21:17:39Z")

</div>

Thank you, this is a very important corrrection indeed, and allows me to advance quite a bit on the understanding of the language. I am still getting used to the idea that variables can things of any kind.

---

<div class="post-metadata">

**Author:** ![affans](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/affans/32/11911_2.png) [@affans](https://discourse.julialang.org/u/affans)\
**Post date:** [January 18, 2019, 2:28pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/11 "2019-01-18T14:28:52Z")

</div>

The not-so-obvious scoping rules you see has been discussed quite a bit over the last year or so. It’s a contentious issue and as far as I am aware, no solution was agreed upon.

> [@REPL and for loops (scope behavior change)](https://discourse.julialang.org/t/repl-and-for-loops-scope-behavior-change/13514/7):
>
> Hi Guys, i’m having the same problem in Jupyter Notebook. I’m creating my own Julia tutorial following the youtube “Intro to Julia” video. In a code cell I made it: n=0 while n \< 10 println(n) n+=1 end And the result was: UndefVarError: n not defined Stacktrace: [1] top-level scope at ./In[18]:3 [inlined] [2] top-level scope at ./none:0 I’ve tried to put the local status in any place but the result still goes wrong, the solution came following @saschatimme instructions (or at leas…

> [@REPL and for loops (scope behavior change)](https://discourse.julialang.org/t/repl-and-for-loops-scope-behavior-change/13514/8):
>
> It is not a bug. It worked in Julia 0.6, in Julia 0.7 it gave a deprecation warning that you must add global, and in 1.0 it throws an error. I really like favba’s idea of starting by introducing functions and teaching them to write tiny functions. Sounds like that’d also end up encouraging good coding habits.

And many more threads.

---

<div class="post-metadata">

**Author:** ![Yousef\_Azizi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yousef_azizi/32/19224_2.png) [@Yousef\_Azizi](https://discourse.julialang.org/u/Yousef_Azizi)\
**Post date:** [January 30, 2022, 10:35pm UTC](https://discourse.julialang.org/t/problem-in-variable-definition-in-loop/19752/12 "2022-01-30T22:35:23Z")

</div>

I encountered same problem and because of my experience with other programming language which usually take more easy about scope specially in loop case, I was a little angry and also disappointed. Based on document, the reason is more clear for me and I think in some cases like software development, it’s not bad to restrict user, but still somehow it’s a hard decision.  
One way to using function and avoiding issue with more localization of code. In original document use an example and use global variable to handle it, which is very dangerous and it’s better to not be used, because of general consequence of global parameter.  
Anyway, thanks to discussing this issue, for many hours I was struggling with this issue and this discussion help me a lot 🙂
