Procedures and Functions
Procedures and functions are named modules of code. Their primary purpose is to subdivide large, complex programming
tasks into smaller, simpler ones. Both procedures and functions have a structure similar to that of a program,
and can declare constants, types, variables, and nested procedures and functions, just like a program, as shown
here:
procedure
<ProcName>;
<constant-definitions>
<type-definitions>
<variable-definitions>
<nested-procedure-definitions>
begin
<statements>
end;
A function is like a procedure except it always returns a value of some type; typically, a function's return value
is the result of calculations based on values passed to the function at runtime.
Calling Procedures and Functions
A procedure is called explicitly with a statement that consists only of the procedure's name; a function is called
implicitly by using its name in an expression within a statement (often an assignment statement). For example:
program
ProcsAndFuncts;
var N
: integer;
procedure
SayHello;
begin
Writeln ('Hello!');
end; { SayHello }
function
Seventeen: integer;
begin
Seventeen := 17;
end; { Seventeen }
begin
{ ProcsAndFuncts }
SayHello; {
calling procedure SayHello }
N := Seventeen; { calling function Seventeen
}
end. { ProcsAndFuncts }
Returning from a Procedure or Function
A procedure or function returns program flow to the calling routine when the last statement in the routine is executed
or, alternatively, when the EXIT statement is encountered.
Local Variables
Any variables declared in a procedure or function are said to be local to that routine. Because of the way these
variables are allocated on the stack when the routine is called and then deallocated when the routine returns,
local variables have a lifetime equal to the duration of the call. In addition, as with global variables, the value
of a local variable is undefined upon entry to a procedure or function. For example:
program
VariableLifetimeDemo;
procedure
TestProc;
var N
: integer;
begin
Writeln( N );
N := 66;
end; { TestProc }
begin
{ VariableLifetimeDemo }
TestProc;
TestProc;
TestProc;
end. { VariableLifetimeDemo }
The output produced by this program is unpredictable, as each call of TestProc may result in any integer value
being printed out. The assignment of 66 to N doesn't "stick."
Parameter Passing
An important concept in procedure and function usage is parameter passing, the process by which information is
sent to (and optionally returned from) a program's procedures and functions.
Recursion
A procedure or function can legally call itself; this process is called recursion, and allows the creation of subtle
and compact algorithms.