Definition
A global variable is a variable that can be read and assigned at any function in the entire program, including functions declared in other.fc files,
as long as those .fc files are imported after the global
variable declaration. It is possible to use global variables imported from other .fc files.
Global variables are useful for remembering values across functions, without the need to pass those values as arguments to every single function in the program.
Under the hood, global variables in FunC are stored inside the tuple of the c7 TVM control register,
with a maximum limit of 31 variables.
Declaration
Global variables are declared using theglobal keyword, followed by the variable’s type and name. For example:
op of type (int, int) -> int. In other words, op can store a function that receives two arguments and returns an integer.
Here is an example that uses global variable op:
check_commutative and add, in addition to the program entry point main.
Function check_commutative checks if the operator stored in the global variable op satisfies the commutative property for the specified inputs a and b.
Function add, adds its two inputs.
Function main assigns the addition function add to the global variable op. Then, it verifies the commutativity of addition for the specific values: 2, 3.
In FunC, you can omit the type of global variables. In this case, the compiler determines the type based on how the variable is used. Equivalently,
instead of declaring the type, you can use the var keyword as a replacement for the type.
For example, in the previous program you can declare the variable op as:
.fc files.
For example, the following does not compile, because the second declaration changes the type of A from int to cell:
Multiple declarations
FunC allows users to declare multiple global variables using a singleglobal keyword.
The following example:
Restrictions on declarations
A local variable cannot have the same name of a previously declared global variable but only if their types differ. The following example does not compile, because the local variableC of type int has the same name as the global variable C of type cell,
and int and cell are different types.
int C = 3; is not declaring a new local variable, but instead assigning value 3 to the global variable C.