The If .. then .. else.. prototype syntax is
_________________________________________________________________________________________________________
If then statements
___________________________________________________________________
The expression between the if and then keywords must have a Boolean result type.
If the expression evaluates to True then the statement following the then keyword is
executed.
If the expression evaluates to False, then the statement following the else keyword is executed, if
it is present.
Some points to note:
- Be aware of the fact that the boolean expression by default will be short-cut evaluated,
meaning that the evaluation will be stopped at the point where the outcome is known
with certainty.
- Also, before the else keyword, no semicolon (;) is allowed, but all statements can be
compound statements.
- In nested If.. then .. else constructs, some ambiguity may araise as to which else
statement pairs with which if statement. The rule is that the else keyword matches
the first if keyword (searching backwards) not already matched by an else keyword.
For example:
If exp1 Then
If exp2 then
Stat1
else
stat2;
Despite its appearance, the statement is syntactically equivalent to
If exp1 Then
begin
If exp2 then
Stat1
else
stat2
end;
and not to
{ NOT EQUIVALENT }
If exp1 Then
begin
If exp2 then
Stat1
end
else
stat2;
If it is this latter construct which is needed, the begin and end keywords must be present. When in
doubt, it is better to add them.
The following is a valid statement:
If Today in [Monday..Friday] then
WriteLn (’Must work harder’)
else
WriteLn (’Take a day off.’);