The reserved word
case starts a clause where alternatives are chosen.
The general structure of
case-clauses looks like this:
case selector of caseValue0: <statement>; caseValue1,caseValue7: <statement>; caseValue10..caseValue20: <statement>; else <statements>; end;
The following constraints have to be met:
- The data type of
selectorhas to be an ordinal type. FreePascal additionally allows strings.
- All case values have to be the same data type as
- They have to be constant expressions, i.e. known at compile-time.
case-labels have to be mutually disjoint. For every discrete value there applies exactly one or no cases.
case-clause has to have at least one
case-statements can have at most one anonymous cases (at most one
The actual order of
case-labels is not relevant.
They may be ascending, descending, or mixed up, it does not matter.
Originally, standard Pascal also set the constraint, that all possible values of the selector have to have a corresponding match. This is no longer the case with modern compilers.
case can have both, imperative and declarative meanings, depending on where it is written.
The former are “statements”, whereas the latter start a “variant part” of records.
1program asciiTest(input, output, stderr); 2 3var 4 c: char; 5 6begin 7 read(c); 8 case ord(c) of 9 // empty statement, so the control characters are not 10 // considered by the else-branch as non-ASCII-characters 11 0..$1F, $7F: ; 12 $20..$7E: 13 begin 14 writeLn('You entered an ASCII printable character.'); 15 end; 16 else 17 begin 18 writeLn('You entered a non-ASCII character.'); 19 end; 20 end; 21end.
case-statements accept expressions as selector.
Instead of writing
else the word
otherwise is allowed, too.
This is an Extended Pascal extension.
While the same semantics can be achieved by consecutive
then-branches, utilizing a
case-statement allows the code generator to optimize the branch selection.
There is no “fall-through” as it is the case with other languages such as shell or C.
In Pascal exactly one case matches, is processed, and program flow continues after the final
end of the
break-statement with its special meaning only appears in loops.
variant part in records
record may contain a variant part.
case-selector has to be the name of a data type, but an identifier for accessing the current variant can be provided, too.
1program variantRecordDemo(input, output, stderr); 2 3type 4 sex = (female, male); 5 clothingSize = record 6 // FIXED PART 7 shoulderWidth: word; 8 armLength: word; 9 bustGirth: word; 10 waistSize: word; 11 hipMeasurement: word; 12 // VARIABLE PART 13 case body: sex of 14 female: ( 15 underbustMeasure: word; 16 ); 17 male: ( 18 ); 19 end; 20begin 21end.
casestatement” in the “FreePascal reference manual”
case” as part of the “Object Pascal introduction”