Skip to main content
Mathematics LibreTexts

4.6: Variable Scope

  • Page ID
    63969
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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:

    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

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

    Local and Global Variables

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

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

    • Was this article helpful?