Lesson 15 · 15 of 20
var and const parameters · Pascal
Pass Pascal parameters by value, by reference with var, and read-only with const, and return several results from one procedure.

A plain parameter is passed by value: the procedure gets a copy. AddBonus sets bonus := 0, yet the main program's bonus is still 30 after the call.
With `var` in front, the parameter is the caller's own variable (passed by reference): whatever the procedure does shows up outside. That is why score goes from 120 to 150. A var parameter needs a variable; AddBonus(120, 30) would not compile.
var is also the way to return several results: SplitTime takes 197 seconds and fills in both mins and secs, something a function, with its single Result, cannot do directly.
`const` marks a read-only parameter: if Show tried to change player, the compiler would report an error. With strings and records it is also more efficient, as no copy is made. It is good practice to use it for anything you will not modify.
Code · main.pas
program main;// score is var (the caller's own variable); bonus is just a copy.procedure AddBonus(var score: Integer; bonus: Integer);begin score := score + bonus; bonus := 0;end;// var parameters let a procedure hand back several results.procedure SplitTime(total: Integer; var mins, secs: Integer);begin mins := total div 60; secs := total mod 60;end;// const: read-only, and the string is not copied.procedure Show(const player: String; score: Integer);begin WriteLn(player, ': ', score, ' points');end;var score, bonus, mins, secs: Integer;begin score := 120; bonus := 30; AddBonus(score, bonus); Show('Ana', score); WriteLn('Bonus after the call: ', bonus); SplitTime(197, mins, secs); WriteLn('Lap time: ', mins, ' min ', secs, ' s');end.Output · fpc main.pas && ./main
Ana: 150 points Bonus after the call: 30 Lap time: 3 min 17 s
Key points
- With nothing in front, a parameter is a copy.
varworks on the caller's variable.- With
var, a procedure can hand back several values. conststops the parameter being changed and avoids copies.
Exercise
Write a Swap(var a, b: Integer) procedure that swaps two variables, and use it to sort two scores, ana and leo, from lowest to highest.