C++ – switch case vs if else

c++compilationif-statementswitch-statement

I was wondering if there was any difference in the way the following code was compiled into assembly. I've heard that switch-case is more efficient than if else, but in this example I am not quite sure if that would be the case.

if(x==1){
...
}else if(x==2){
...
}else{
...
}

and

switch(x){
 case 1:
 ...
 break;

 case 2:
 ...
 break;

 default:
 ...
}

Best Solution

A compiler will sometimes turn a switch into a jump-table, if the entries are contiguous (or nearly so). Or it could theoretically use a binary search to find the case instead of a linear series of tests, which would be faster if you had a large number of cases.

On the other hand, there's nothing stopping the compiler from doing the same optimisations on the same code converted into if/else.

So on a good compiler, switch can be faster in some cases. On a very good compiler, they'd be the same.