To Switch Or Not To Switch

When it comes to making selections in C programming, the obvious first choice of most programmers is the if,else combination. This can become a hassle when there are multiple choices with different or similar outcomes. A simple example of this is outputting the number of days in a month. You could do:

if (month == "January") cout << 31;
else if (leapyear == false && month == "February) cout << 28;
etc...

This becomes tedious rather quickly. Of course you can combine some months, but you really aren't saving yourself much code:

if (month == "January" || month == "March" || month == "May ... ) cout << 31;
etc...

Another option to consider is the switch statement, which can cut down on the amount of code you have to write considerably. A switch is composed of two main parts; the switch expression, and the case statements. The above example looks something like this:

switch (month) {
case "January": cout << 31; break;
case "February": cout << 28 + leapyear; break;
case "March": etc... }

Notice, the variable you are checking is the switch expression, while each case statement is a possible value contained in that variable. The break statement is very important. It signifies the end of the code to be executed. Without it, the program would evaluate all code from the case statement to the end of the switch block. You probably also noticed that February's case is a bit odd. A boolean variable (leapyear) will evaluate in an arithmetic equation as a 1 when set to true, or a 0 when set to false. Hence, when leapyear is set to true, February will output 29.

I'm sure you're wondering where the advantage is in using a switch statement over if-else. One of the most important features of the case statements is that they can be stacked. For example:

switch (month) {
case "January": case "March": case "May" ... cout << 31; break;
case "February": etc...; break;
case "April": case "June": etc...; break; }

In this case, if month is equal to any of the case statements, then the following code is executed. One final point to consider is the default statement. This is basically just an else that is executed if none of the case statements evaluates to true:

switch (month) {
case "January": case "March": case "May" ... cout << 31; break;
case "February": etc...
case "April": case "June": etc...
default: cout << "not a month"; }

This is useful for error checking as shown above, but if you are certain that an invalid value is not possible, then the default statement can be used for code optimization:

switch (month) {
case "January": case "March": case "May" ... cout << 31; break;
case "February": etc...
default: cout << 30; }


0 comments:

Post a Comment