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
expression1thenif
expression2then
statement1else
statement2;
There would appear to be two ways to parse this:
if
expression1 then [ if
expression2then
statement1else
statement2 ];
if
expression1then [ if
expression2then
statement1 ] else
statement2;
The compiler always parses in the first way. That is, in real code, the statement
if ... { expression1} then
if ... {expression2} then
... {statement1}
else
... {statement2}
is
equivalent to
if ... {expression1} then
begin
if ... {expression2} then
... {statement1}
else
... {statement2}
end;
The rule is that nested conditionals are parsed starting from the innermost conditional, with each else bound to the
nearest available if on its left. To force the compiler to read our example in the second way, you would have to write
it explicitly as
if ... {expression1} then
begin
if ... {expression2} then
... {statement1}
end
end
else
... {statement2};
Dostları ilə paylaş: