If Statements

There are two forms of if statement: if...then and the if...then...else. The syntax of an if...then statement is ifexpressionthen statement where expression returns a Boolean value. If expression is True, then statement is executed; otherwise it is not. For example, if J <> 0 then Result := I / J;

The syntax of an if...then...else statement is ifexpressionthen statementl elsestatement2

where expression returns a Boolean value. If expression is True, then statementl is executed; otherwise statement2 is executed. For example, if J = 0 then Exit else

The then and else clauses contain one statement each, but it can be a structured statement. For example, if J <> o 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 ifexpression1thenifexpression2thenstatement1elsestatement2;

There would appear to be two ways to parse this:

ifexpressionl then [ ifexpression2thenstatement1elsestatement2 ];

ifexpressionlthen [ ifexpression2thenstatement1 ] elsestatement2;

The compiler always parses in the first way. That is, in real code, the statement if ... { expressionl} then if ... (expression2) then

  • statementl) else
  • statement2)

is equivalent to if ... (expressionl) then begin if ... (expression2} then

  • statementl} else
  • statement2}


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 ... {expressionl} then begin if ... {expression2} then

  • statementl} end end else
  • statement2};
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment