Information must be
stored inside
a computer programusingvariables
There are different kinds of
information:
Some information is used
only within
one function
Example:
A running (loop) index in
a for-loop
I call these variablesshort term storage variables.
Some information is used
by
multiple functions
Example:
StackTop for
a stack data structure will be
used by push( ) and
pop( )
I call these variableslong term storage variables.
To accommodatebothshort term/long term storage
requirements,
high level programming language provide
different kinds
of variables !!!
Example:Java provides:
Class variables
to storepermanent (very long term) information
Instance variables
(in objects) to
storelong term information
(e.g.: you can create an object and use the object
in different instance methods)
Parameter variables
to storeshort term information
(used to pass information
to one function)
Local variables
to storeshort term information
(used to store information
used by one function)
Review: life time and
scope of variables
Variables in
a high level programming languagealways have
2 properties:
Life time:
When is a
variablecreated
(= begins to exist)
When is a
variabledestroyed
(= ends to exist)
Scope:
Scope =
the portion of the
computer program where
a variable can
be accessed (= used in expressions)
Life time of variables
Variables are
created at certain time during
the execution of a program
Variables are
destroyed
when the program reaches a certain
location during
the execution
Life time of a variable:
Life time of a
variablex =
time between the
creation of the variable
x and the
destruction of the variable
x
Scope of variables
The scope of a variablex
is the part of the program in which the
execution of that part
of the program
can accessed the variablex.
The scope of a
variable is always a
sub-range of the life time of the
variable !
Warning: scope of variables
in C
The Scoping rules
for variables in Cmore complex than
those in Java
This is because:
Gosling had simplified
the scoping rules of
C by
forbidding
you to define
multiple local and parameter
variables
with the
same name inside a
method in Java.
Gosling thinks that
variables with the same name
inside a method will
confuse
the programmer...
We will first discuss the
life time of the variables
Then we will discuss the
scope of the
variables in
C.