**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:

switch(value) {
	case 0:
		// some code
		break;
	case 1:
		// some code
		break;
	// ...
	default:
		// some code
		break;
}

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.

always@(*x) // 7-segment display
begin
	case(x)
		4'b0000: H = 7'b0111111;
		4'b0001: H = 7'b0000110
		// ...
		default: H = 7'b0000000;

Multiple cases

In break-based languages, we can switch with multiple cases by avoiding the break:

switch (value) {
	case 0:
	case 1:
	case 2:
		// some code
		break;
	default:
		break;
}

And in Rust, we can chain several patterns in a single match:

match value {
	0 | 1 | 2 => // some code
	_ => // some code
}

Footnotes

  1. From this video by Low Level Learning.