Switch Statements
Switch statements in Spice can be used to execute different code paths based on the value of a variable. This is similar to switch
statements in other languages, but with some differences. The expression in the switch
statement can be of type int
, long
, short
, byte
, char
or bool
and the individual match expressions need to be literals of the respective type.
Usage¶
Here's a simple example for an switch
statement:
case
branch gets executed, if the value of the switch
statement matches the value of the case branch. If no case branch matches, the optional default
branch gets executed. The default branch must be the last branch in the switch
statement, the order of case branches does not matter. Optional parentheses
As with the for, foreach and while loops, the parentheses around the head of the switch
statement are optional.
Let's take a look at a switch statement:
Spice | |
---|---|
Fallthrough¶
In Spice, the switch
statement does not fall through by default. This means, that you don't need to use the break
keyword to prevent the next case from being executed, like in other languages. In Spice, you have to use the fallthrough
keyword to fall through to the next case branch. This originated from the assumption, that you more often want to execute one branch, instead of having fallthrough behavior.
The fallthrough keyword can be used like this:
Spice | |
---|---|
fallthrough
keyword ensures that in the above example, the case 6, 9
branch gets executed, even though the value of i
is 1
or 2
and the respective branch was executed beforehand.