September 2008 | LINUX For YoU | www.
openItis.
com106
S.
G.
GaneSh
The Joy of
Programming
C
/C++ allows only integer types for use in case
statements.
Why can’t we use floating point numbers?
Because C designers thought that it is not a good idea:...
More
September 2008 | LINUX For YoU | www.
openItis.
com106
S.
G.
GaneSh
The Joy of
Programming
C
/C++ allows only integer types for use in case
statements.
Why can’t we use floating point numbers?
Because C designers thought that it is not a good idea:
checking the exact equality in floating point is not portable
[ref: C99 rationale].
How about string literals? It is allowed in
many languages that evolved from C, such as C#, which is a
useful feature.
Since switch is for integral types, a compiler
can translate it to efficient code, as we will now see.
Which of the two is better: a switch statement or
cascading if-else statements? Well, a switch expresses
the programmer’s intentions more clearly than an if-else
cascade.
Also, you might be surprised to know that a switch
is, in general, more efficient than an equivalent if-else
statement sequence! Why?
The if-else statement is flexible: it can have different
conditions for each ‘if’ statement; also each condition can
have (different)
Less