Switch vs If

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