case
The Case keyword provides a structured equivalent to a sequence of if statements on the same variable. The
Case statement is more elegant, more efficient, and easier to maintain than multiple if nestings. Case is
also used for Records declarations. It is then called a Variant. It provides a means of mapping two or more
differing sets of declarations onto the same section of the record.
Case is used in records when handling different types of dataset for a record, where the datasets have mostly the
same content.
Example
Download This Source for Free Pascal
type
// Declare a fruit record using case to choose the
// diameter of a round fruit, or length and height ohterwise.
TFruit = record
name : string[20];
Case isRound : Boolean of // Choose how to map the next section
True :
(diameter : Single); // Maps to same storage as length
False :
(length : Single; // Maps to same storage as diameter
width : Single);
end;
var
apple, banana, fruit : TFruit;
number : Integer;
Begin
// Calculations can also be used in the case statement
number := 17;
Case number mod 2 of
0 : Writeln(Number,' mod 2 = 0');
1 : Writeln(Number,' mod 2 = 1');
else Writeln(Number,' mod 2 is unknown');
end;
// Set up the apple as round, with appropriate dimensions
apple.name := 'Apple';
apple.isRound := True;
apple.diameter := 3.2;
// Set up the banana as long, with appropriate dimensions
banana.name := 'Banana';
banana.isRound := False;
banana.length := 7.65;
banana.width := 1.3;
// Show the attributes of the apple
fruit := apple;
if fruit.isRound then Writeln(fruit.name,' diameter = ',fruit.diameter)
else Writeln(fruit.name,' length = ',fruit.length,' width = ',fruit.width);
// Show the attributes of the banana
fruit := banana;
if fruit.isRound then Writeln(fruit.name,' diameter = ',fruit.diameter)
else Writeln(fruit.name,' length = ',fruit.length,' width = ',fruit.width);
end.
Output
17 mod 2 = 1
Apple diameter = 3.200000048E+00
Banana length = 7.650000095E+00 width = 1.299999952E+00
See Also
Else,
End,
If,
Record,
Then.