switch
often serves as an alternative to if
. Our first example is equivalent
to the following:
if (mark == 'A') { printf("Well done!\n"); } else if (mark == 'B') { printf("Good effort.\n"); } else if (mark == 'C') { printf("Not bad.\n"); } else if (mark == 'D') { printf("Try harder.\n"); } else if (mark == 'E') { printf("Pathetic!\n"); } else if (mark == 'F') { printf("Loser!\n"); } else { printf("ERROR\n"); }
This if
happens to be shorter than the
switch
, but it can appear more cluttered,
with } else if (mark ==
being repeated several
times. The second example is equivalent to the
following:
if (mark == 'A' || mark == 'B' || mark == 'C') { printf("Pass\n"); } else if (mark == 'D' || mark == 'E' || mark == 'F') { printf("Fail\n"); } else { printf("ERROR\n"); }
…which still has a lot of repetition, as well as
longer lines to manage. switch
can also look better when the controlling expression is
not a simple variable:
switch (get_mark(student_id)) { case 'A': printf("Well done!\n"); break; . . . }
The equivalent if
is not necessarily:
if (get_mark(student_id) == 'A') { printf("Well done!\n"); } else if (get_mark(student_id) == 'B') { . . . }
…because get_mark(student_id)
is now invoked multiple times, and might have side-effects, or be
computationally expensive. It would be much better to
store its result:
{ int mark = get_mark(student_id); if (mark == 'A') { printf("Well done!\n"); } else if (mark == 'B') { . . . } }
Not all if
chains can be represented by an
alternative switch
.
For example, these if
s classify a score using
inequalities:
if (score < 10) { printf("Why did you bother?\n"); } else if (score > 90) { printf("Excellent!\n"); } else { printf("Mediocre.\n"); }
Even if the score has a discrete set of values, so
that you could write the code as a switch
,
it would have poor readability.
One problem with choosing to use switch
is then later deciding to make the test more
sophisticated, and thus discovering that you need an
if
.