Variable
→ Thing that changes. See Constant and Change for cool idea.
CS241E: “Abstraction of a storage location that can hold a value”.
Kinds of Variables
- Global variables
- Defined outside of any enclosing function/class/struct
- Come into existence when declared and die at the end of the program
- Local variables
- Come into existence when the function is called
- Member / instance variables
Variable Lookup Order
Variable Instances
This is only important at low-level development, considered in the context of CS241E.
Consider the function factorial(x) = x if (x < 2) else x * factorial(x-1)
.
When we run factorial(x)
, there is a single variable x
. However, when we actually compute the value, say factorial(3)
, we actually get three variable instances during computation: x=3
, x=2
, x=1
.
Depending on the type of variable, we have different implementations:
Variable Kind | Extent* | Implementation |
---|---|---|
Global Variable | Entire Execution of program | Fixed memory address (label) |
Local Variable | Execution of the procedure (LIFO) | [[notes/Stack |
Field of an object/record | From creation time to last use | [[notes/Heap |
Extent (of a variable) = the time interval during program execution when the variable can be accessed