Don Burgess
Don Burgess

Reputation: 21

Use of global declaration inside if statement (Julia Code)

Why do I have declare variables global when they are in same if elseif else block? What am I missing?


function f(N)

for n in 0:N
    if n == 0
        fibonacci_n = 0
        fibonacci_n_1 = fibonacci_n
    elseif n == 1
        fibonacci_n = 1
        fibonacci_n_1 = fibonacci_n
        fibonacci_n_2 = fibonacci_n_1
    else
        global fibonacci_n_1, fibonacci_n_2
        fibonacci_n = fibonacci_n_1 + fibonacci_n_2
        fibonacci_n_1 = fibonacci_n
        fibonacci_n_2 = fibonacci_n_1
    end        
    @printf "%5i %10i\n" n fibonacci_n
end

end

Upvotes: 2

Views: 947

Answers (1)

hckr
hckr

Reputation: 5583

The problem you have is not really about global scope and you do not have to declare anything global here. global keyword is necessary if you would like a write access to a global variable.

Your global keyword introduce new global bindings fibonacci_n_1 and fibonacci_n_2. It does not matter where you put the global keyword in the scope. You can even access the last value of fibonacci_n_1 and fibonacci_n_2 after the function terminates: try f(5); println(fibonacci_n_1) in global scope.

If you remove the global declaration in your function, fibonacci_n_1 and fibonacci_n_2 will be defined in the local scope of your for-loop. Hence, there will not be a global scope access issue. The issue you have, however, will be about the following behavior of variables introduced in loop blocks.

for loops, while loops, and Comprehensions have the following behavior: any new variables introduced in their body scopes are freshly allocated for each loop iteration, as if the loop body were surrounded by a let block

https://docs.julialang.org/en/v1/manual/variables-and-scoping/#For-Loops-and-Comprehensions-1

This means that you cannot access a variable's value or binding in the previous iteration if you introduce that variable inside the for-loop. This is not similar to the behavior of variables introduced in Python or MATLAB loops.

Instead, you can define such variables outside the for loop but inside the function.

function f(N)

fibonacci_n, fibonacci_n_1, fibonacci_n_2 = 0, 0, 0
for n in 0:N
    if n == 0
        fibonacci_n = 0
        fibonacci_n_1 = fibonacci_n
    elseif n == 1
        fibonacci_n = 1
        fibonacci_n_2 = fibonacci_n_1
        fibonacci_n_1 = fibonacci_n
    else
        fibonacci_n = fibonacci_n_1 + fibonacci_n_2
        fibonacci_n_2 = fibonacci_n_1
        fibonacci_n_1 = fibonacci_n
    end        
    @printf "%5i %10i\n" n fibonacci_n
end

end

For more relevant discussion about scope of variables in Julia, please see the Scope of Variables section of Julia documentation.

Upvotes: 4

Related Questions