Quick start manual

4-24
Delphi Language Guide
Declarations and statements
The syntax of an if...then...else statement is
if expression then statement
1
else statement
2
where expression returns a Boolean value. If expression is True, then statement
1
is
executed; otherwise statement
2
is executed. For example,
if J = 0 then
Exit
else
Result := I/J;
The then and else clauses contain one statement each, but it can be a structured
statement. For example,
if J <> 0 then
begin
Result := I/J;
Count := Count + 1;
end
else if Count = Last then
Done := True
else
Exit;
Notice that there is never a semicolon between the then clause and the word else.
You can place a semicolon after an entire if statement to separate it from the next
statement in its block, but the then and else clauses require nothing more than a
space or carriage return between them. Placing a semicolon immediately before else
(in an if statement) is a common programming error.
A special difficulty arises in connection with nested if statements. The problem arises
because some if statements have else clauses while others do not, but the syntax for
the two kinds of statement is otherwise the same. In a series of nested conditionals
where there are fewer else clauses than if statements, it may not seem clear which
else clauses are bound to which ifs. Consider a statement of the form
if expression
1
then if expression
2
then statement
1
else statement
2
;
There would appear to be two ways to parse this:
if expression
1
then [ if expression
2
then statement
1
else statement
2
];
if expression
1
then [ if expression
2
then statement
1
] else statement
2
;
The compiler always parses in the first way. That is, in real code, the statement
if ... { expression1 } then
if ... { expression2 } then
... { statement1 }
else
... { statement2 } ;