Switch in Pascal
Here’s the translation into Pascal:
Switch statements express conditionals across many branches.
Here’s a basic switch
.
program SwitchExample;
uses SysUtils;
begin
var i: Integer := 2;
Write('Write ', i, ' as ');
case i of
1: Writeln('one');
2: Writeln('two');
3: Writeln('three');
end;
You can use commas to separate multiple expressions in the same case
statement. We use the optional default
case in this example as well.
case DayOfTheWeek(Now) of
6, 7: Writeln('It's the weekend');
else Writeln('It's a weekday');
end;
switch
without an expression is an alternate way to express if/else logic. Here we also show how the case
expressions can be non-constants.
var t: TDateTime := Now;
case True of
t.Hour < 12: Writeln('It's before noon');
else Writeln('It's after noon');
end;
A type switch
compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t
will have the type corresponding to its clause.
procedure whatAmI(v: Variant);
begin
case VarType(v) of
varBoolean: Writeln('I\'m a bool');
varInteger: Writeln('I\'m an int');
else Writeln('Don\'t know type ', VarType(v));
end;
end;
whatAmI(True);
whatAmI(1);
whatAmI('hey');
end.
To run the program, compile the code using a Pascal compiler (like Free Pascal Compiler) and execute the binary.
$ fpc SwitchExample.pas
$ ./SwitchExample
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type 258
Next example: Arrays.