Next: Summary
Up: The switch statement
Previous: The switch statement
The following statement writes out the day of the week depending on
the value of an integer variable day
. It assumes that day 1 is
Sunday.
switch (day) { case 1 : cout << "Sunday"; break; case 2 : cout << "Monday"; break; case 3 : cout << "Tuesday"; break; case 4 : cout << "Wednesday"; break; case 5 : cout << "Thursday"; break; case 6 : cout << "Friday"; break; case 7 : cout << "Saturday"; break; default : cout << "Not an allowable day number"; break; }
If it has already been ensured that day
takes a value between 1
and 7 then the default
case may be missed out. It is allowable to
associate several case labels with one statement. For example if the
above example is amended to write out whether
day
is a weekday or is part of the weekend:
switch (day) { case 1 : case 7 : cout << "This is a weekend day"; break; case 2 : case 3 : case 4 : case 5 : case 6 : cout << "This is a weekday"; break; default : cout << "Not a legal day"; break; }
Remember that missing out a break
statement causes control to
fall through to the next case label -- this is why for each of the days
2-6 `This is a weekday' will be output. Switches can always be
replaced by nested if-else
statements, but in some cases this may be
more clumsy. For example the weekday/weekend example above could be
written:
if (1 <= day && day <= 7) { if (day == 1 || day == 7) cout << "This is a weekend day"; else cout << "This is a weekday"; } else cout << "Not a legal day";However the first example becomes very tedious--there are eight alternatives! Consider the following:
if (day == 1) cout << "Sunday"; else if (day == 2) cout << "Monday"; else if (day == 3) cout << "Tuesday"; . . else if (day == 7) cout << "Saturday"; else cout << "Not a legal day";