Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Mathematics LibreTexts

4.6: Variable Scope

( \newcommand{\kernel}{\mathrm{null}\,}\)

If you are using the command line julia (also called the REPL) or iJulia, then entering x=6 will create x as a global variable, even without saying so explicitly. If we consider the factorial function above:

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

function fact(n::Integer) 
  prod=1
  for i=1:n 
    prod *= i
  end
  prod
end
function fact(n::Integer) 
  prod=1
  for i=1:n 
    prod *= i
  end
  prod
end
 

then recall that n is the function argument and the variable prod is actually declared locally implicitly and it is good form to say it is local by

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

function fact(n::Integer) 
  local prod=1
  for i=1:n
    prod *= i 
  end
  prod
end
function fact(n::Integer) 
  local prod=1
  for i=1:n
    prod *= i 
  end
  prod
end
 

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

2*prod
2*prod
 

Local and Global Variables

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

x=3
function f()
  local x=2
  x
end
f()
x=3
function f()
  local x=2
  x
end
f()
 

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

x
x
 

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

x=3
function g()
  global x=2
  x
end
g()
x=3
function g()
  global x=2
  x
end
g()
 

Login with LibreOne to run this code cell interactively.

If you have already signed in, please refresh the page.

x
x
 

4.6: Variable Scope is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

Support Center

How can we help?