UNIHIVE

Study Hub UNIPORT CSC 288

CSC 288 · Structured Programming

Procedures, functions, parameters and scope

Writing subprograms, value and variable parameters, local and global names, and nesting in Pascal.

Our notes

2 min read

Procedures and functions

  • A procedure performs an action: procedure PrintLine(n: integer);
  • A function returns a value: function Square(x: real): real;

function Square(x: real): real;
begin
  Square := x * x
end;
In standard Pascal the result is given by assigning to the function's name (Free Pascal also allows Result).

Parameters

  • Value parameters (default): a copy is passed; changes inside do not affect the caller.
  • Variable parameters (var): the procedure works on the caller's variable itself.

procedure Swap(var a, b: integer);
var t: integer;
begin
  t := a; a := b; b := t
end;
Calling Swap(x, y) with x = 3, y = 8 leaves x = 8, y = 3. Without var, nothing would change outside.
Use var for results and for large arrays (to avoid copying); use value parameters to protect inputs (or const parameters in Free and Turbo Pascal).

Scope

  • Local variables are declared inside a subprogram and exist only while it runs.
  • Global variables are declared in the main program and seen everywhere, unless hidden by a local with the same name.
  • Pascal allows nested subprograms: an inner one can see the variables of the ones around it (static scope).

Worked example: scope

program ScopeDemo;
var x: integer;
procedure P;
var x: integer;
begin
  x := 5;
  writeln('inside: ', x)
end;
begin
  x := 1;
  P;
  writeln('outside: ', x)
end.
Output: inside: 5, then outside: 1. The local x hides the global one.

Side effects

A function that changes global variables or its var parameters has side effects: the same call can give different results and the code becomes hard to reason about. Keep functions pure where possible.

Forward declarations

Pascal needs a name declared before it is used. When two subprograms call each other, declare one first with forward;.

Exams usually ask

  • Distinguish procedures from functions; write examples of each.
  • Explain value and variable parameters with a trace.
  • Explain local, global and nested scope.

Common mistake

Forgetting var on an output parameter: the procedure changes its own copy and the caller sees nothing.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

No reading links here yet

Our team adds free books, videos and practice for each topic, and opens every link before it goes up.

All CSC 288 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.