**switch
statements are built-in conditional chains in some programming languages. They are akin to chains of if
and else
statements.
For example, if we’re searching for an option with multiple if
statements, it could take multiple cycles, which could be slower or take more resources on embedded systems. Under the hood, the compiler does some number manipulations and finds the condition we’re looking for without doing comparisons. In terms of time complexity, if
statements use time, but switch
statements use .1 So switch
statements use hash tables. But compilers that optimise well should also turn many-branch if
statements to hash tables anyways.
In many languages (including C/C++), we must have break
statements to jump out of the switch
statement. If we don’t break
we’ll instead run the next case and fall through (which may be intended). The default
case runs if no cases match — we should always have one.
Here’s a sample set of statements in C:
Rust’s match
statement functions as a switch statement that is exhaustive. The compiler will ensure that every possible pattern is covered. We can add a default case with other
.
In Verilog
We have an analogous term in Verilog, for case
statements within always blocks. default
cases are especially important for mapping mux inputs that may not be explicitly mentioned in our cases.
Multiple cases
In break
-based languages, we can switch with multiple cases by avoiding the break
:
And in Rust, we can chain several patterns in a single match
:
Footnotes
-
From this video by Low Level Learning. ↩