Quote:Original post by smr
A switch statement and an if-else-else if wouldn't necessarily compile out the same. A switch statement always compares against one expression that can be pre-calculated before any comparisons are made:
*** Source Snippet Removed ***
Examples one and two could potentially generate the same code. The left hand expression ((x + 100) % 4) doesn't need to be re-evaluated for each if statement, so it would work like a switch statement.
In example three the expression needs to be re-evaluated for each if statement. This would compile differently than a switch statement.
The compiler is a lot smarter than you think it is. Your third example:
/* example three */if(x - 10 == 100) printf("one hundred\n");else if(x + 100 == 10) printf("ten\n");
could easily be changed to:
if(x == 110) printf("one hundred\n");else if(x == -90) printf("ten\n");
And the compiler will easily catch such conditions and evaluate them so.