Properties of Variables
- Name: string of characters with some constraints (e.g. max length)
- Type: indicates range of values that are allowed as well as operations that are available.
- Address: memory address to which the variable is associated (also known as l-value)
- Value: contents of memory associated with variable (also known as r-value)
- Lifetime: time during which the variable is allocated a specific memory location (between allocation / deallocation)
Lifetime Classes
There are 4 classes of variables according to their lifetime:
Static Lifetime
Static: bound to a memory location before program execution begins and until it ends. This is efficient as there is no allocation / deallocation at run time.
Link to originalStack Dynamic Lifetime
Stack dynamic: allocated when declaration of variable is processed at run time.
Link to originalExplicit Heap-Dynamic Lifetime
Explicit heap-dynamic: nameless memory cells which are allocated / deallocated by program instructions, using pointers:
// C++ memory explicit heap-dynamic allocation int * v = new int; // allocation delete v; // deallocationIn Java, objects are explicit heap-dynamic and can be accessed through reference variables but there is no way to destroy them explicitly, implicit garbage collection is used.
Link to originalImplicit Heap-Dynamic Lifetime
Implicit heap-dynamic variables: bound to storage only when they are assigned values. For example, strings / arrays in JavaScript, this is flexible but can be difficult to detect errors.
Link to original
Scope
Variable Scope
Scope: the range of instructions in which the variable is visible
Link to original
- Local variables are those declared in the block of the program that is executed.
- Global variables are those that are visible but not local.
Static Scope
Static Scope is when scope is determined before the execution of a program (at compile time). When a variable is referenced, the compiler looks for its declaration in the same block, then ascending parents, etc. If no declaration is found, we throw an error.
Link to original
Dynamic Scope
Dynamic Scope is when scope is determined during the run time of a program. It depends on the call sequence of sub routines. This prevents us from doing static type-checking and may make programs very difficult to understand. Some shell scripting languages use dynamic scoping.
Link to original
Variable assignment generally uses the syntax variable-name = expression, but this may vary between languages. The value of the expression is stored in the variable. In typed languages, the expression and variable must have compatible types.