Julia global Keyword | Creating a global variable in Julia

Keywords in Julia are reserved words whose value is pre-defined to the compiler and can not be changed by the user. These words have a specific meaning and perform their specific operation on execution.

'global' keyword in Julia is used to access a variable that is defined in the global scope. It makes the variable where it is used as its current scope and refers to the global variable of that name.
Syntax:

var1 = value1
loop condition
    statement
    global var1 = value2
    statement
end

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Julia program to illustrate 
# the use of global variable
  
for i in 1:10
    global x = i
end
  
# Accessing global variable 
# from outside of the loop
println(x)

chevron_right


Output:

10

With the use of global variable, the value of variable x can be accessed from anywhere in the code.



Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Julia program to illustrate 
# the use of global variable
  
x = 0
  
# Defining function
function check_global()
    for i in 1:5
      
        # Re-defining global variable
        global x = i * 2
        println(x)
    end
    println(x)
end
  
# Function call
check_global()

chevron_right


Output:

2
4
6
8
10
10

In the above code, it can be seen that the loop will redefine the value of the global variable and when it is called outside of the loop, the updated value is printed.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.