The semicolon, ; is used to indicate the end of a statement. It is mandatory for most statements, voluntary in some statements, and forbidden in one particular statement.
(In order to explain usage, where Pascal keywords are referred to in the text of this article, they are shown in UPPER case. Program listings will use lower case.)
The semicolon is generally mandatory, and is required after every statement. The places where it is optional are
- before an END statement
- before the period at the end of a PROGRAM or UNIT
The places where a semicolon is forbidden are
- Before a BEGIN statement which begins a compound statement
- Before an immediately following ELSE clause of a nested IF statement
It is generally forbidden before the ELSE clause in an IF statement or a CASE statement. However, in the case of a nested IF statement it may be required before the ELSE, if there is an ELSE applying to another IF statement earlier in the program text and the particular IF is not ended by an ELSE statement. This will be explained below.
A semicolon is forbidden before the ELSE clause which applies to the immediately last IF statement in order that the compiler can know where that IF statement ends. For example
(*0001*) if continuance then (*0002*) if separated then (*0003*) Condition(a) (*0004*) else (*0005*) if combined then (*0006*) Condition(b) (*0007*) else (*0008*) Condition(c); (*0009*) Calculate_fee;
For this example, the semi colon is forbidden on line 3 (otherwise the ELSE on line 4 would apply to the IF on line 1).
If there was going to be a BEGIN between lines 1 and 2, and an END after line 8, then a semicolon would be forbidden on line 1.
Because line 6 has no semi colon, the ELSE on line 7 applies to the IF on line 5. If line 6 ended with a semi colon, then the ELSE on line 7 would apply to the IF on line 1 (the ELSE on line 4 applies to the IF on line 2). Thus the semicolon is forbidden in this context in order to get that result.
However, if you wanted the ELSE to apply to line 1, the semicolon would be mandatory on line 6, in order to "close" the IF on line 5.
If there was an IF statement above line 1, the semi colon on line 8 closes the IF statement on line 1, and if an ELSE were to be placed after line 8, it would not apply to the IF statement on line 1.
It may be preferable to enclose all statements inside an IF statement with a BEGIN / END block if there might be a question as to which ELSE applies to which IF, in a set of nested IF statements.