Use if .. then or if .. then .. else to run corresponding code when the condition is true. Unlike C-style languages: the conditional expression in Pascal does not need parentheses.
var
A: Integer;
B: boolean;
begin
// Only one statement after condition, no begin end required
if A > 0 then
DoSomething;
// Multiple statements after condition, must wrap with begin end
if A > 0 then
begin
DoSomething;
AndDoSomethingMore;
end;
// Single-line if-else structure
if A > 10 then
DoSomething
else
DoSomethingElse;
// Identical logic to above: store comparison result into boolean variable first
B := A > 10;
if B then
DoSomething
else
DoSomethingElse;
end;Code language: JavaScript (javascript)
else Matching Rule
else binds to the nearest unmatched if. The code below works as expected:
if A <> 0 then
if B <> 0 then
AIsNonzeroAndBToo
else
AIsNonzeroButBIsZero;Code language: HTML, XML (xml)
The else here belongs to the inner if B <> 0.
Nested if without block wrapping is syntactically valid but hard to read. It’s recommended to wrap inner nested logic with begin … end for clear logical boundaries; even with messy indentation, readers can easily distinguish scopes and avoid bugs when adding/removing branches.
Optimized standard writing style:
if A <> 0 then
begin
if B <> 0 then
AIsNonzeroAndBToo
else
AIsNonzeroButBIsZero;
end;Code language: HTML, XML (xml)
- No parentheses around if conditions (mandatory in C/C++/Java, opposite in Pascal);
- Omit
begin endif only one line after then; mandatory for multiple lines; elsematches the nearest inner if; always use blocks for nested conditions to eliminate ambiguity;- Comparison expressions (e.g.
A>10) can be directly assigned to boolean variables.
Below is a runnable full example: score grading system
Logic rules:
- ≥90 → A
- ≥80 and <90 → B
- ≥60 and <80 → C
- <60 → D
{$ifdef FPC} {$mode objfpc} {$H+} {$endif}
{$codepage utf8}
program ScoreLevel;
var
score: Integer;
begin
Write('Please enter exam score: ');
ReadLn(score);
if score >= 90 then
Writeln('Grade: A')
else if score >= 80 then
Writeln('Grade: B')
else if score >= 60 then
Writeln('Grade: C')
else
Writeln('Grade: D');
ReadLn;
end.Code language: PHP (php)
Compile and run
Please enter exam score: 96
Grade: A
The program prompts for score input and outputs corresponding grade.
Non-English text may show garbled characters, add this line: {$codepage utf8}
We can also wrap grade calculation into a function.
{$ifdef FPC} {$mode objfpc} {$H+} {$endif}
{$codepage utf8}
program ScoreLevelFunc;
function GetLevel(s: Integer): string;
begin
if s >= 90 then
Result := 'A'
else if s >= 80 then
Result := 'B'
else if s >= 60 then
Result := 'C'
else
Result := 'D';
end;
var
score: Integer;
begin
Write('Your score: ');
ReadLn(score);
Writeln('Your grade: ', GetLevel(score));
ReadLn;
end.Code language: PHP (php)

if conditional judgment