Global variables within loop in Julia

Written by Administrator on Thursday May 14, 2020

Julia has unusial definition of global variables within loop cycles.

For example, in other languages, it's possible to use outer variable and change it inside for-loop construction (JavaScrip code):

JavaScript code

var i;
for (i = 0;i < 12;i++) {
  i+=1;
} 
console.log(i);

This code will result in:

12

Python code

y = 0;
for x in range(0,5):
    y += 1

print(y)

output:

5

In Jula this construction works in a little bit different way. In order to avoid variable naming conflicts, Julia uses different variable scoping system. Reason it very easy to understand: several functions can have have arguments with the same name and referring to the same thing. Even different part of code can use the same name (even without referring to the same entity).

The only thing you have to keep in mind while programming in Jula, is that global scope variables are defined inside loops. It sounds strange, but it has reasons (read above). It's supposed, that one can understand many things on example. Let's check one:

Julia code

function count()
    global y=0
    for i = 1:15
            y +=1
    end
end

count()

println(y)

You see, that global variable y is defined inside for loop. And latter usage of this global variable is shown with println.

Category: julia Tags: julia loops variables_scope