Lesson 7 · 7 of 20
The case statement · Pascal
Choose between many values with case in Pascal: days of the week, grade ranges and the menu of a vending machine.

`case` expression `of` compares a value with a list of options and runs the one that matches. It reads better than an else if chain when every condition asks about the same variable.
Each option can be one value, several separated by commas (6, 7) or a range (1..5). The final else catches everything that does not match. Unlike if, the option before this else does take a semicolon.
Ranges keep the grade table short: 83 falls into 80..89 and the result is B. Options cannot overlap; if a value appears in two of them, the compiler reports an error.
case works with any ordinal type: integers, Char, Boolean and the enumerated types of lesson 17, but not with real numbers. In the vending machine, 'b' picks the coffee. That case has no else, so if no option matched, nothing would happen.
Every case is closed with its own `end;`, even though there is no begin.
Code · main.pas
program main;var day, score: Integer; option: Char;begin day := 6; case day of 1..5: WriteLn('Day ', day, ': working day'); 6, 7: WriteLn('Day ', day, ': weekend'); else WriteLn('Day ', day, ': not a day of the week'); end; // Ranges keep a grade table short. score := 83; case score of 90..100: WriteLn(score, ' points: A'); 80..89: WriteLn(score, ' points: B'); 70..79: WriteLn(score, ' points: C'); else WriteLn(score, ' points: keep practising'); end; // case also works with Char: a vending machine. option := 'b'; case option of 'a': WriteLn('Water: 1.00'); 'b': WriteLn('Coffee: 1.50'); 'c': WriteLn('Juice: 2.00'); end;end.Output · fpc main.pas && ./main
Day 6: weekend 83 points: B Coffee: 1.50
Key points
case x ofpicks an option based on the value ofx.- Options can be lists (
6, 7) and ranges (1..5). elsecatches the values that are not listed.- It only works with ordinal types, not real numbers.
- Every
caseends withend;.
Exercise
Add a case for a month number (month) that prints how many days it has: 28 for 2; 30 for 4, 6, 9 and 11; and 31 for the rest.