Chapter 4 Lecture Notes 9/22/99
Pascal Procedures and Scope
In Pascal you can assign a name of a sequence of statements by means of something called a procedure declaration. Using the procedure name inside the body of the program will then have the same effect as executing the sequence of statements.
Example:
program test (input, output);
procedure AddNumbers;
var
a,b:integer;
begin {AddNumbers }
write ('Enter an integer: ');
readln (a);
write ('Enter another integer: ');
readln (b);
write ('The sum is ',a+b);
end; {AddNumbers }
begin
writeln ('this is a test');
AddNumbers;
end.
Then from your program, you can call AddNumbers like this:
AddNumbers;
As you can see, procedures can have variables in their heading just like programs can. To pass data to procedures, you can use parameter lists. Former parameter are the names and types of parameters listed in the procedure heading. Actual parameters are the variables or constants that you actually send to the procedure.
Example:
program test (input, output);
var
a,b:integer;
procedure AddNumbers (a:integer;b:integer);
begin {AddNumbers }
write ('The sum is ',a+b);
end; {AddNumbers }
begin
writeln ('this is a test');
write ('Enter an integer: ');
readln (a);
write ('Enter another integer: ');
readln (b);
AddNumbers(a,b);
end.
This program does the same thing, but we pass in the values from the main program instead of getting them from within the procedure.
Passing parameters this way is called passing by value. That values that are stored in the actual parameters are copied to two new variables in the procedure. Changing these values in the procedure will not affect the contents of the actual parameters.
For example:
program test (input,output); var x:integer; procedure changevar(a:integer); begin a:=a+1; writeln (‘in changevar, a is ‘,a); end; begin x:=2; changevar (x); writeln (‘in the program, x is ‘,x); end.Output:
in changevar, a is 3 in the program, x is 2
However, this does not let the procedure send data back to the calling program or procedure. In order to do this, you must use call by variable or call by reference. To do this, setup the former parameters of your procedure like this:
program test (input,output); var x:integer; procedure changevar(var a:integer); begin a:=a+1; writeln (‘in changevar, a is ‘,a); end; begin x:=2; changevar (x); writeln (‘in the program, x is ‘,x); end.
Output:
in changevar, a is 3 in the program, x is 3
Shortcut:
If you have multiple former parameter of the same type, you can combine them like this:
procedure (a,b,c : integer);
or
procedure (var a,b,c : integer);