Difference between Switch and if-else ladder in ANSI C

There are few restrictions with usage of  switch. These are:

(a)A float expression cannot be tested using a switch statement.

(b) Switch cases cannot have variable expressions (x +3 : ).

(c)Multiple cases cannot use same expressions.

switch(x)

{

Case 3:

Case 1 + 2:

}

 

Above mentioned restrictions are disadvantages with a switch, especially since there weren’t any such limitations with if-else. But still Switch are used because—switch works faster than an equivalent if-else ladder. This is because the compiler generates a jump table for a switch during compilation. As a result, during execution it simply refers the jump table to decide which case should be executed, rather than actually checking which case is satisfied. As against this, if-elses are slower because they are evaluated at execution time. A switch with 5 cases would work faster than an equivalent if-else ladder. Also, a switch with 2 cases would work slower than if – else ladder. Why? If the 10th case is satisfied then jump table would be referred and statements for the 10th case would be executed. As against this, in an if-else ladder 10 conditions would be evaluated at execution time, which makes it slow. Note that a lookup in the jump table is faster than evaluation of a condition, especially if the condition is complex.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]
If you enjoyed this post, make sure you subscribe to my RSS feed!

Speak Your Mind

*


two × = 2