Section 5.1 - If Statements

Inside a subprogram body, between the "is" and the "end <name>", is a sequence_of_statements. A sequence_of_statements is simply - well - a sequence of statements, each terminated with a semicolon. There are many different kinds of statements; we've already seen assignment statements and procedure call statements. We'll now examine a few other kinds of statements, starting with the if statement.

If statements determine if some condition is true, and then execute some sequence of statements depending on that determination. Here's a trivial example that determines if A is equal to B; if it is, A receives the value of B plus one. If A isn't equal to B, A receives the value of B minus one:

 if A = B then
    A := B + 1;
    A := B - 1;
 end if;

Here's the full BNF for the if statement:

if_statement ::=
  "if" condition "then"
  {"elsif" condition "then"
  "end if;"

Like other algorithmic languages, if `condition' is true the `then' part is executed. Otherwise, the elsif clauses (if any) are checked in first-to-last order, again looking for a true condition. Finally, if none of the conditions are true, the `else' clause is executed (if there's an "else" clause).

Notice that the keyword "then" is mandatory (it doesn't exist in C or C++).


What is the final value of A in the following sequence of statements?

 A := 5;
 B := 6;
 if A > B then
  A := 7;
  A := A - 2;
 end if;
  1. 3
  2. 5
  3. 7

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 5 outline

David A. Wheeler (

The master copy of this file is at "".