Control Flow

6.1 if..then..else

⚠️ A semicolon before else is a syntax error.

if Score >= 90 then
  Grade := 'A'
else if Score >= 80 then        // no semicolon before else!
  Grade := 'B'
else
begin
  Grade := 'C';
  Writeln('Needs improvement');
end;

6.2 case..of

case works on ordinal types (integers, chars, enums, Boolean), not strings. For strings, use IndexStr/IndexText (System.StrUtils) with case, or if-chains.

case Key of
  'a'..'z': Writeln('lowercase');
  'A'..'Z': Writeln('uppercase');
  '0'..'9': Writeln('digit');
  ' ', #9: Writeln('whitespace');
else
  Writeln('other');
end;

case Status of
  ckRed: StopTraffic;
  ckGreen: GoTraffic;
  ckBlue: ;                       // empty statement
end;
case IndexText(Cmd, ['start', 'stop', 'status']) of
  0: Start;
  1: Stop;
  2: ShowStatus;
else
  Writeln('Unknown command');
end;

6.3 Loops

The for loop variable must be a local ordinal. It can't be modified inside the loop, and its value is undefined after the loop.

Break (exit the loop), Continue (next iteration), Exit (leave the routine), Exit(Value) (return a value from a function), Halt (terminate the program), goto (requires a label declaration; avoid it).

for I := 1 to 10 do Write(I, ' ');
for I := 10 downto 1 do Write(I, ' ');
for var Item in MyList do Writeln(Item);           // for..in over arrays, strings, sets, collections
for var Ch in 'Hello' do Write(Ch, '-');

while not EOF(F) do
begin
  Readln(F, Line);
  Process(Line);
end;

repeat
  Write('Enter a positive number: ');
  Readln(N);
until N > 0;                                       // repeat..until always runs at least once (no begin/end needed)

6.4 with Statement (Use Carefully)

with can cause ambiguity and debugging problems. Many style guides discourage it. Inline variables are a clearer alternative: var C := Customer;.

with Customer do
begin
  Name := 'Ana';
  City := 'Pune';
end;