Decisions: if & case
The dangling else binds to the nearest if.
9.1 if-then-else
The dangling else binds to the nearest if. Use begin ... end to make intent clear:
if Score >= 90 then
Grade := 'A'
else if Score >= 80 then
Grade := 'B'
else if Score >= 70 then
Grade := 'C'
else
Grade := 'F';if A > 0 then
begin
if B > 0 then
Writeln('both positive');
end
else
Writeln('A not positive');9.2 Boolean expressions directly
// Instead of: if X > 0 then IsPositive := True else IsPositive := False;
IsPositive := X > 0;
// Instead of: if Done = True then ...
if Done then ...9.3 Conditional expressions
IfThen(Cond, A, B) from Math (numbers) or StrUtils (strings) — both arguments are always evaluated.
Delphi 13 Florence adds a true conditional expression: X := if A > B then A else B;. FPC does not support it.
9.4 case
case selects on an ordinal expression with constant labels, lists, and ranges:
Labels must be constants, unique, and non-overlapping.
else (or otherwise in FPC/ISO) handles unmatched values; without it, nothing happens (ISO Pascal treats an unmatched value as an error).
Each branch is a single statement — use begin ... end for several.
FPC additionally supports case on strings; Delphi does not.
case Ch of
'a'..'z', 'A'..'Z': Writeln('letter');
'0'..'9': Writeln('digit');
' ', #9: Writeln('whitespace');
else
Writeln('other');
end;case Month of
1, 3, 5, 7, 8, 10, 12: Days := 31;
4, 6, 9, 11: Days := 30;
2: if IsLeapYear(Year) then Days := 29 else Days := 28;
end;{$mode objfpc}{$H+}
case LowerCase(Command) of
'start': StartServer;
'stop': StopServer;
else
Writeln('Unknown command');
end;