See keyword: global
A global variable is one that may be accessed anywhere within Octave.
This is in contrast to a local variable which can only be accessed outside
of its current context if it is passed explicitly, such as by including it as a
parameter when calling a function
(fcn (local_var1, local_var2)
).
A variable is declared global by using a global
declaration statement.
The following statements are all global declarations.
global a global a b global c = 2 global d = 3 e f = 5
Note that the global
qualifier extends only to the next end-of-statement
indicator which could be a comma (‘,’), semicolon (‘;’), or newline
(‘'\n'’). For example, the following code declares one global variable,
a, and one local variable b to which the value 1 is assigned.
global a, b = 1
A global variable may only be initialized once in a global
statement.
For example, after executing the following code
global gvar = 1 global gvar = 2
the value of the global variable gvar
is 1, not 2. Issuing a
‘clear gvar’ command does not change the above behavior, but
‘clear all’ does.
It is necessary declare a variable as global within a function body in order to access the one universal variable. For example,
global x function f () x = 1; endfunction f ()
does not set the value of the global variable x
to 1. Instead,
a local variable, with name x
, is created and assigned the value of 1.
In order to change the value of the global variable x
, you must also
declare it to be global within the function body, like this
function f () global x; x = 1; endfunction
Passing a global variable in a function parameter list will make a local copy and not modify the global value. For example, given the function
function f (x) x = 0 endfunction
and the definition of x
as a global variable at the top level,
global x = 13
the expression
f (x)
will display the value of x
from inside the function as 0, but the value
of x
at the top level remains unchanged, because the function works with
a copy of its argument.
Programming Note: While global variables occasionally are the right solution to a coding problem, modern best practice discourages their use. Code which relies on global variables may behave unpredictably between different users and can be difficult to debug. This is because global variables can introduce systemic changes so that localizing a bug to a particular function, or to a particular loop within a function, becomes difficult.