Unit 7 - Variables Flashcards
In imperative programming, a variable
stands for a computer memory cell (or a collection of memory cells).
Such a cell can store different values at different times and
thus it makes sense to assign a new value to a variable, overwriting the old value. It is therefore called a mutable variable.
A variable in functional or logical programming
refers to a single value during its lifetime, although unknown at the time of writing. A mathematical variable cannot change its value once it is defined. It is therefore called an immutable variable.
An imperative variable can be characterised by the
following six aspects:
- Name, ie an identifier used in the program;
- Scope, ie the portion of the program where one is allowed to refer to the variable
using its name; - Type, ie a classifying type restricting the values (optional);
- Lifetime(s), ie zero, one or more periods of time during execution when a piece of
memory exists for storing a value of this variable; - Reference(s), ie the address of a piece of memory where a value of the variable is
stored; this could be either one reference for each lifetime or a relative reference
that applies to multiple lifetimes; - Value(s) (at each moment, there is one value for each lifetime).
A variable declaration is a piece of program text which
- announces the existence of a variable with a given name,
- (optionally) states the type of the variable and
- (optionally) assigns an initial value to the variable.
The scope of a variable is the
portion of the program in which the programmer can refer to the variable.
If a scope is determined statically
it is usually defined by the smallest block that contains its declaration.
Languages in which variables have no classifying type
Lisp, Python,
JavaScript and PHP
Static type checking
The compiler tries to analyse all assignments to the variable and checks that the values assigned will always be compatible with the variable’s classifying type.
Dynamic type checking
The compiler inserts a code that will check every assignment at run time.
a classifying type is a subtype of another one if
its permitted values are also permitted values of the supertype.