Julia local Keyword | Creating a local 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.

'local' keyword in Julia is used to create a variable of a limited scope whose value is local to the scope of the block in which it is defined.

Syntax:

var1 = value1
loop condition
    statement
    local var1
    statement
end

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



ERROR: LoadError: UndefVarError: x not defined

Above code generates error because the socpe of variable x is limited to the scope of for-loop in which it is defined.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Julia program to illustrate 
# the use of local variable
  
# Defining function
function check_local()
    x = 0
    for i in 1:5
      
        # Creating local variable
        local x
        x = i * 2
        println(x)
    end
    println(x)
end
  
# Function call
check_local()

chevron_right


Output:

2
4
6
8
10
0

In the above code, it can be seen that when the value of x is printed within the loop, the output is as per condition, but when the value of x is printed outside the scope of for-loop, the value of x is again 0 as assigned earlier. This shows that the scope of the local variable remains limited to the block in which it is defined.

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.