Playing with Switches

While coding, you need to control over something, so we have “Control Structures” in our language. Most of the programing language have control structures. And you are building an application, so you (not you exactly, your code) need to make a decision, then your code start comparing things and take the correct decision and moves ahead. It uses conditional statements for comparing stuffs and take action as per the logic. When we say conditional statements, normally some people understand if, else stuff. And they just ignore the switch statement. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. But I have seen some people using long series of else if/elseif instead using switch. Here I am going to discuss few tricks with the Switches (switch statement).

Switch statement is available in most programing languages. I work on PHP mostly, so I am going to show you examples in PHP code. You can learn about PHP syntax of switch statement on PHP Manual, as I am not going to explain them here. Also look at the comments on that page, they contains many valuable information and tricks.

Why should we use switch statements?

Before I share some tricks, let me explain you why should we use switch statement, instead of using if else. It’s true that you can achieve anything you do with switch statement with if else, but switch statement works faster. In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

Execute same statements for more than one cases

Let’s start with some tricks. If you want to execute same statements for more than one cases, then you don’t need to write two those statements twice under both the cases. The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

switch ($i) {
case 0:
case 1:
case 2:
    echo "i is less than 3 but not negative";
    break;
case 3:
    echo "i is 3";
}

If you want to execute some statements under a case and those same statements are also need to be executed after few other statements under a case, then you can only write those different statements first, then do not write the common statements and do not put break after those statements. Now start other case and put those common statements after this case.

switch ($i) {
case 0:
case 1:
    echo "i is 1 and ";
case 2:
    echo "i is less than 3 but not negative";
    break;
case 3:
    echo "i is 3";
}

Use default case anywhere you want

Some people might believe that default case can only be used at the end of the switch block. Before few days, I was never used default case anywhere expect end of the switch statement. It is not that the variable used in the switch statement will be compared to each case one by one and if it does not match with any case, then it will execute statements under default case. As in a switch statement, the condition is evaluated only once and the result is compared to each case statement, if it does not match with any case, then it directly goes to the default case. It does not matter where you have write default case. But I encourage you to write default case at the end, unless it is not highly needed, for simplicity. Sometimes you might like to put default case in between other cases, if you follow any logical order to put the statements under any case.

And the master trick

If you combine above two tricks, you will get this master trick. So first, you will not put break after the statements of a case and second, you can put default case after that. So if the above case matches, then the statements under this case will be executed and also the statements under the default case will be executed. This can be really helpful in many situations. For examples, for a certain case you want to show a warning and execute the statements under default case, then you can use this trick.

$drinks = array('Milk', 'Coffee', 'Mango Juice', 'Orange Juice', 'Apple Juice', 'Whiskey');

foreach ($drinks as $drink) {
    switch ($drink) {
    case 'Coffee':
        echo "Warning: Too much caffeine is not good for health. 
"; default: echo $drink . " is a nice drink.
"; break; case 'Whiskey': echo "Alcohol is bad for our health.
"; } }

These are the few tricks for switch statements of Control Structures. I will share few other tricks on Control Structures. Please subscribe to my blog and be in touch. I am waiting for your comments here. Please comment if you like this or not. If you have any tricks, then please share those here.

Image credit: Fickr – artwork_rebelDerelict – Light Switch


Posted

in

by

Comments

One response to “Playing with Switches”

  1. gautom Avatar

    Its very nice to see you writing on smaller technicalities with so much of details. I am looking forward for more like these.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.