Switch vs If

I have the following program that could be expressed in two ways

First using Switch Statements:

switch (value1.tag) {
    .verbatim_literal_delimiter => {
        // Handling Code...
    },
    .keyword_true, .keyword_false => {
       switch (value2.tag) {
            .eof => // Handling Code
            .newline => //Handling Code
            else => {}
        }
    },
    else => {},
}
// Deal with Other Cases Specially

Second Using If Statements

if (value1.tag==.verbatim_literal_delimiter) {
        // Handling Code...
}
if (value1.tag == keyword_true or value1.tag == .keyword_false) {
       if (value2.tag == .eof) {
            // Handling Code
       } else if (value2.tag == .newline) {
            //Handling Code
       }
}
// Deal with other cases Generally

I believe these two constructs are semantically equivalent. My question is this, other than preference, is there a reason to pick one over the other? I feel like sometimes I might reach for the switch statement too soon. Is there a good rule of thumb about when/why to use one over the other?

3 Likes

I think it’s more of a matter of taste and readability preferences, as nowadays any modern compiler can produce the same quality of code for both since GCC 11 i believe

GCC-11 - Release Note

  • A series of conditional expressions that compare the same variable can be transformed into a switch statement if each of them contains a comparison expression.

Example:
int IsHTMLWhitespace(int aChar) { return aChar == 0x0009 || aChar == 0x000A || aChar == 0x000C || aChar == 0x000D || aChar == 0x0020; }
This statement can be transformed into a switch statement and then expanded into a bit-test.

Personally I usually reach for a switch statements when I have more than 3/4 if statements, and exclusively use switch statements for error handling, or when I use an enum. but feel free to do as you like :slight_smile:

But there is an argument to be made that on certain target maybe the switch statements might be more often optimize to a jump table when the target hasn’t implemented that for if/else too.

5 Likes

If the switch can be made to cover all possible cases (which is not the case in your examples), I would opt for it, because it makes it clear your code is exhaustive. An if cannot in general convey the same assurance.

7 Likes

I’d also add that if’s afford compound/complex checks. If it’s just straight value comparison then a switch is probably clearer (especially if gets above 3/4 statements like you mentioned).

3 Likes