Compound statement

Description

Compound statements group a statement-sequence (i.e. one or more statements) into a single statement, and are executed as follows:

  1. Program execution is transfered to the first statement in the statement-sequence.
  2. Program execution is transfered to the statements in the statement-sequence in the order in which they occur in the program text, unless diverted by one of the statements executed.
  3. Execution of the compound statement is terminated when either the execution of the last statement in the statement-sequence is terminated, or when one of the statements in the statement-sequence transfers program execution to a statement outside of the compound statement.
You usually use compound statements when the rules of Pascal say that only one statement is allowed at a particular point in the program, but you want to put more than one statement there. The solution to this problem is to put the statements into a compound statement.

Example

For example look at the program fragment below:

   write('Do you want to continue');
   readln(answer);
   if (answer = 'n') or (answer = 'N') then
     begin
        writeln('Program terminated by user');
        halt
     end

here we want to write a message to the screen and stop if the user answers n or N, but this requires two statements and the then-part of an if statement allows only a single statement. The solution as you can see is to put the two statements into a compound statement.

Syntax

(NOTE: for clarity some parts of the syntax are omitted, see Irie Pascal Grammar for the full syntax):

   compound-statement = 'begin' statement-sequence 'end'

   statement-sequence = statement { ';' statement }