A compiler translates C code to machine code. On assembler level, there is no such thing as if
, else
or switch
. There are just conditional branches and non-conditional branches.
So, no, the compiler will never do anything like what you are suggesting, because an if-else
that can be replaced by a switch
will already result in identical machine code, no matter which one you wrote. There is no middle "convert C to C" step.
For this reason, switch
is kind of an obscure language feature, since it is in theory completely redundant. It is subjective whether a switch
results in more readable or less readable code. It can do either, on a case-by-case basis.
Special case:
There exists a common optimization of switch
statements that the compiler can do when all the case
labels are adjacent integer constants, and that is to replace the whole switch
with an array of function pointers. It can then simply use the switch
condition as array index to determine which function to call. No comparisons needed. This is quite a radical optimization, because it removes numerous comparisons and thereby speeds up the code, improves branch prediction, etc.
The very same optimization is possible if you have a chain of if - else if
, like so:
if(n==0)
{ }
else if(n==1)
{ }
else if(n==2)
{ }
...
This can also get optimized into an array of function pointers, just like if it were written as a switch
.