# Global variable cannot be read within if-else-loop

**URL:** <https://discourse.julialang.org/t/global-variable-cannot-be-read-within-if-else-loop/37932>\
**Category:** General Usage\
**Created:** [April 20, 2020, 9:35pm UTC](https://discourse.julialang.org/t/global-variable-cannot-be-read-within-if-else-loop/37932 "2020-04-20T21:35:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kendrawu](https://avatars.discourse-cdn.com/v4/letter/k/e495f1/32.png) [@kendrawu](https://discourse.julialang.org/u/kendrawu)\
**Post date:** [April 20, 2020, 9:35pm UTC](https://discourse.julialang.org/t/global-variable-cannot-be-read-within-if-else-loop/37932/1 "2020-04-20T21:35:26Z")

</div>

Here is a sample code I have created:

```julia
function fn_update_a(a, b, c, d)
   a = fn(c,d)
   b = vcat(b,a)
   return a, b
end

for isim in 1:10
   a = fn(c, d)
   if isim==1
      b = deepcopy(a)
   else
      a=1
      println(b)
      (a,b) = fn_update_a(a,b,c,d)
   end
end

```

My question is why there is an error saying “b is not defined” at line after a=1 when b=deepcopy(a)?

---

<div class="post-metadata">

**Author:** ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)\
**Post date:** [April 20, 2020, 9:40pm UTC](https://discourse.julialang.org/t/global-variable-cannot-be-read-within-if-else-loop/37932/2 "2020-04-20T21:40:26Z")

</div>

Because `b = deepcopy(a)` will only be run `if isim == 1`, and `println(b)` will be run otherwise (when `isim != 1`).  
The `b` definitions are local to that iteration of the loop. You could write `global b`.

---

<div class="post-metadata">

**Author:** ![kendrawu](https://avatars.discourse-cdn.com/v4/letter/k/e495f1/32.png) [@kendrawu](https://discourse.julialang.org/u/kendrawu)\
**Post date:** [April 21, 2020, 5:20am UTC](https://discourse.julialang.org/t/global-variable-cannot-be-read-within-if-else-loop/37932/3 "2020-04-21T05:20:59Z")

</div>

Thank you.
