Chapter 11: Appendix
This appendix collects reference material for Pascal programming: a list of reserved words, some common compiler directives, and tips and best practices for writing efficient, maintainable Pascal code.
Pascal reserved words
Reserved words are predefined, so you can’t use them as identifiers such as variable or procedure names. Here is a list of them:
and array begin case const
div do downto else end
file for function goto if
in label mod nil not
of or packed procedure program
record repeat set then to
type until var while with
Common compiler directives
Compiler directives are special instructions that change how the compiler behaves.
Syntax
A compiler directive is usually written between {$ and }.
Examples
-
$Iincludes a file.{$I filename.inc} -
$Rturns range checking on or off.{$R+} { Enable range checking } {$R-} { Disable range checking } -
$Qdoes the same for overflow checking.{$Q+} { Enable overflow checking } {$Q-} { Disable overflow checking } -
$Msets the stack and heap sizes.{$M 16384,0,655360} -
$DEFINEand$UNDEFdefine and undefine symbols.{$DEFINE DEBUG} {$UNDEF DEBUG}
Tips and best practices
Use meaningful variable names
Descriptive names for variables, procedures, functions, and other identifiers make your code easier to read and maintain.
var
totalAmount: real;
studentName: string;
Comment your code
Use comments to explain what your code is for, especially where the logic is complex. They help other people (and you) understand it.
{ Calculate the total amount after applying the discount }
totalAmount := price - (price * discount / 100);
Consistent indentation
Indent your code consistently so it’s easier to read. Two or four spaces per level of indentation is typical.
if condition then
begin
statement1;
statement2;
end;
Avoid magic numbers
Instead of hard-coded numbers (magic numbers), use constants with meaningful names.
const
MaxStudents = 50;
var
studentCount: integer;
begin
if studentCount > MaxStudents then
writeln('Error: Exceeds maximum number of students');
end;
Modularize your code
Break your code into smaller, reusable procedures and functions. Modular code like this is easier to test and maintain.
procedure PrintGreeting(name: string);
begin
writeln('Hello, ', name);
end;
begin
PrintGreeting('Alice');
end.
Handle errors gracefully
Use error handling to deal with exceptions and other unexpected situations in your code.
try
result := StrToInt(input);
except
on E: EConvertError do
writeln('Invalid number format');
end;
Optimize for performance
Avoid unnecessary calculations, and choose efficient algorithms and data structures.
for i := 1 to n do
result := result + values[i];
Test your code thoroughly
Test with both normal and edge cases to make sure your code works correctly in every situation.
procedure TestAddition;
begin
Assert(Add(2, 2) = 4);
Assert(Add(-1, 1) = 0);
Assert(Add(0, 0) = 0);
end;