Lecture 15: of variables and procedures
Global variables are variables that can be used everywhere in the program
Local variables are only defined inside a procedure or function.
|With this new information, it is much more clear which variable we can use when. Inside procedures and functions we can use the global and the local variables. Outside the procedures and functions we can only use the global variables. Remember again what we learned in lecture12 (see the image on the right). The main program cannot use the variables of the modules, but the other way around is allowed.|
|Warning: try to avoid the use of global variables in procedures as much as possible. The reason why is simple. If we want to copy the procedure for another program this will be more difficult, becuase in the new program probably will not have the same global variables. Using only local variables in procedures is therefore much better. If you want to use the global variables, pass them as parameters to the procedure. Ideally, a procedure is a stand-alone unit.|
|One more rule, typically for PASCAL and languages alike (single-pass
compilers): variables can only be used in places AFTER their declaration
in the program, so, if we put the declaration of a variable after a procedure,
this procedure cannot use the variable.
Let's take a look at some examples. First a program of lecture 13:
FUNCTION Square(r: real): real;
(* local variable localr *)
var localr: real;
localr := r*r;
x := localr;
Square := localr;
x := 4.0;
y := Square(x);
Variable x is a local and a global variable.
Inside the procedure, the local variable
will be used.
|When local and global variables exist with the same name, the local
variable has higher priority and will therefore be used inside the procedure.
Anyway, this is confusing, so always try to avoid using the same identifier
Some languages do not have the difference between local and global variables (for example BASIC). This will mean that we cannot use the same name for a variable twice.
Passsing by reference:
On the other hand, if we do want to change the value of the variable used in calling the procedure, we can specify this at the definition of the procedure by placing the word Var in front of every parameter that we want to change permanently:
PROCEDURE WriteSquare(Var p: real);
p := p*p;
If we now run the program, the output will be
because the value of x has changed simultaneously with the value of the parameter p.