Email: Password: Remember Me | Create Account (Free)

Back to Subject List

Old thread has been locked -- no new posts accepted in this thread
???
04/15/03 13:19
Read: times


 
#43443 - RE: Switch Case and If Else If
Responding to: ???'s previous message
"the C book that I use said that SWITCH CASE method is designed for character only and not suitable for numbering"

I certainly hope that it didn't - that's complete nonsense!
K&R:
"The switch statement causes control to be transferred to one of several statements depending on the value of an expression, which must have integral type" (my emphasis).

Obviously, a particular implementation may be more or less efficient with certain expression types; eg an 8051, being an 8-bit device, will always be more efficient with 8-bit operations!

switch statements can be inefficient if you have only a very small number of cases with very widely spaced values - known as "sparse" values.

The major distinction between a switch and a series of if...elses is that the switch evaluates the condition only once, whereas each if...else requires that a condition be evaluated. [1]

Thus a series of if...elses can be used to give priority to certain conditions, or to give improved speed to the most common condition(s).
A switch should be used where the conditions have (nominally) equal probabilities, and/or you need consistent execution times for all conditions.


[1] actually, some compilers may implement some switch statements as a series of ifs - especially "sparse" ones!
I think Keil does.

List of 8 messages in thread
TopicAuthorDate
Switch Case and If Else If            01/01/70 00:00      
   RE: Switch Case and If Else If            01/01/70 00:00      
      RE: Switch Case and If Else If            01/01/70 00:00      
         RE: Switch Case and If Else If            01/01/70 00:00      
   RE: Switch Case and If Else If            01/01/70 00:00      
      RE: Switch Case and If Else If            01/01/70 00:00      
         RE: Switch Case, abhishek            01/01/70 00:00      
            RE: Switch Case, abhishek            01/01/70 00:00      

Back to Subject List