Switch in Scilab

Switch statements express conditionals across many branches.

Here’s a basic switch.

i = 2;
disp("Write " + string(i) + " as ");
switch i
    case 1
        disp("one")
    case 2
        disp("two")
    case 3
        disp("three")
end

You can use commas to separate multiple expressions in the same case statement. We use the optional else case in this example as well.

weekday = weekday(date(), "long");
switch weekday
    case {"Saturday", "Sunday"}
        disp("It's the weekend")
    else
        disp("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.

t = localtime();
switch
    case t(4) < 12
        disp("It's before noon")
    else
        disp("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.

Note: Scilab does not have explicit type switches, so we mimic type checking with conditions.

function whatAmI(i)
    if typeof(i) == 'boolean' then
        disp("I'm a bool")
    elseif typeof(i) == 'constant' then
        disp("I'm an int")
    else
        disp("Don't know type " + typeof(i))
    end
endfunction

whatAmI(%T)
whatAmI(1)
whatAmI("hey")
// Output expected
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string