Sunday, September 27, 2015

Decisions Using the Switch Statement

You can also make decisions using the switch statment. It looks like this:

switch (exponent) {
    case 0 :
        // do nothing
        break;
    case 1 :
        input = input * 10;
        break;
    case 2 :
        input = input * 100;
        break;
    case 3 :
        input = input * 1000;
        break;
    default :
        // do nothing
        break;
}

The above code implements simple exponentiation for languages that do not support it natively. Note that each case is an integer. The general rule is that the different cases must be types that can be converted to integer at compile time. The computer science term for such types is "enumerable." Integers, characters, and enumerations would be valid here. (An enumeration is just a way of giving names to different integers, like constant literals.) Characters are valid enumerable types because they can be considered a restricted set of integers. For example, the letter 'A' evaluates to the integer 65. See the ASCII character set for more information.



The reason for this restriction is that traditional languages convert the various cases to a table that has numerical indexes. For this reason, types such as strings and floating point numbers (which include the double types) are not valid cases in a switch statement. Neither are compound types, such as structs, arrays, and objects.

However, modern scripting languages like PHP and JavaScript do allow the use of non-enumerable types within the cases. The following code would be valid PHP or JavaScript code:

switch ($opcode) {
    case "ADD" :
        // do add stuff here;
        break;
    case "SUB" :
        // do subtract stuff here;
        break;
    case "LOAD" :
        // do load stuff here;
        break;
    case "STORE" :
        // do store stuff here;
        break;
    default :
        // do nothing
        break;
}

Note that all of the switch statement examples include the default case. If none of the other cases applies, the code after the default label is executed. It is good practice to include a default label. You should generate an error message if it makes sense to do so. In my classes, I will mark you down if you do not include the default label.

Also, each one of these case and default labels has a break statement. The break statement indicates where the code for a particular case ends. The break statement must always be included. Without the break statement, the code will fall through, which means that the code in the next case will continue to be executed. You usually do not want this. In the rare case that you do want this, it is a good idea to include a comment indicating that you want the fall through and why. In my classes, I will mark you down if you do not include the break statements. (And your code will probably not work anyway.)


No comments:

Post a Comment