Reputation: 9114
What guidelines can be followed when deciding between if - else if - else and switch - case?
Some examples of equivalent couples of structures. Or are they?
int a;
#define const1 42
#define const2 666
if(a == const1){};
switch(a){
case const1: {}
break;
}
if(a == const1){}
else {}
switch(a){
case const1: {}
break;
default: {}
break;
}
if(a == const1){}
else if(a == const2){}
else {}
switch(a){
case const1: {}
break;
case const2: {}
break;
default: {}
break;
}
From here on, I think switch is definitely superior in terms of both readability and performance.
As a matter of fact, I am currently at the last situation, trying to decide which way to go.
Upvotes: 0
Views: 1050
Reputation: 8195
If they just involve evaluating a variable, testing it and executing a statement depending on that, there's no difference in the logic, and any decent compiler can see that.
I tried the same test (a check for 32
) with an if
and a switch
, and gcc, even with all optimisation turned off generated:
For the if
:
movl a(%rip), %eax
cmpl $32, %eax
jne .L2
movl $1, %eax
jmp .L3
for the switch
:
movl a(%rip), %eax
cmpl $32, %eax
jne .L6
movl $1, %eax
jmp .L3
Of course, if you're going to test the same integer for lots of values, a switch
is more readable -- that's what it's intended for.
Upvotes: 3