If you keep reading from the link you gave:

The variable relation is declared inside the if block, but used outside. 
However, when depending on this behavior, make sure all possible code paths 
define a value for the variable. The following change to the above function 
results in a runtime error

julia> function test(x,y)
         if x < y
           relation = "less than"
         elseif x == y
           relation = "equal to"
         end
         println("x is ", relation, " y.")
       endtest (generic function with 1 method)
julia> test(1,2)x is less than y.
julia> test(2,1)ERROR: UndefVarError: relation not defined
 in test at none:7

You will see that when i==2 you won't define x and therefore you will get 
the runtime error. 

On Monday, February 8, 2016 at 5:41:40 AM UTC-6, David van Leeuwen wrote:
>
> Hello, 
>
> According to 
> http://docs.julialang.org/en/release-0.4/manual/control-flow/#man-conditional-evaluation
>  variables 
> in if blocks do not introduce lexical scope, and hence are available 
> afterwards.   This makes sense and is what I need. 
>
> However, it seems afterwards relates to position in the encapsulating 
> block, and not to execution time. 
>
> function testif()
>     for i in 1:2
>         if i==1
>             x = 0
>         end
>         if x==2
>             println(x)
>         end
>     end
> end
>
>
> This code gives me an undefined `x` in the print statement, where I would 
> have expected `x` to be initialized in the first iteration.  It seems I 
> need to define `x` outside the for loop, even though I don't need it there. 
>  
>
> Is this interpretation in Julia intentional?
>
> Cheers, 
>
> ---david
>
>

Reply via email to