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?
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
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
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.
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.
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).