Learn Pascal
3Ca - IF

The IF statement allows you to branch based on the result of a Boolean operation. The one-way branch format is:
     if BooleanExpression then
        StatementIfTrue;

If the Boolean expression evaluates to true, the statement executes. Otherwise, it is skipped.

The IF statement accepts only one statement. If you would like to branch to a compound statement, you must use a begin-end to enclose the statements:
     if BooleanExpression then
        begin

           Statement1;
           Statement2
        end;

There is also a two-way selection:
     if BooleanExpression then
        StatementIfTrue
     else
        StatementIfFalse;

If the Boolean expression evaluates to FALSE, the statement following the else will be performed. Note that you may NOT use a semicolon after the statement preceding the else. That causes the computer to treat it as a one-way selection, leaving it to wonder where the else came from.

If you need multi-way selection, simply nest if statements:

   if Condition1 then
      Statement1
   else
      if Condition2 then
         Statement2
      else
         Statement3;

Be careful with nesting. Sometimes the computer won't do what you want it to do:

   if Condition1 then
      if Condition2 then
         Statement2
   else
      Statement1;
The else is always matched with the most recent if, so the computer interprets the preceding block of code as:
   if Condition1 then
      if Condition2 then
         Statement2
      else
         Statement1;
which is absolutely not what you wanted. You can get by with a null statement:
   if Condition1 then
      if Condition2 then
         Statement2
      else
   else
      Statement1;
or you could use a begin-end block. But the best way to clean up the code would be to rewrite the condition.
   if not Condition1 then
      Statement1
   else
      if Condition2 then
         Statement2;
This example illustrates where the not operator comes in very handy. If Condition1 had been a Boolean like:
     (not(a < b) or (c + 3 > 6)) and g
reversing the expression would be much more difficult than NOTting it.


Previous lesson

Next lesson

Contents

Index

e-mail me


taoyue@mit.edu
Copyright © 1997-2001 Tao Yue. All rights reserved.