Switch statement
The "switch" statement is similar to a series of "If...else" statements. 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. This is exactly what the switch statement is for. The syntax of the "switch" statement will be:Let's discuss the above syntax step by step. Let's consider the simple script given below using the if, elseif, else statements.
Now we will use the switch statement for the above task. First we will use only the "switch" statement and see what happens.
Now, let's see what the output will be. Suppose, the value of "i" is 1. The output will be:
i equals 1 i equals 2which is certainly not the desired one. The switch statement is always used along with break. When the expression value matches any case value, it performs the code associated with it and when it encounters break statement, it comes out of the switch loop. If the break statement is missing, the pointer will perform all the statements subsequent to the matching case statement. In our example above, the value of "i" was 1. So the code underneath it was performed but since it did not encounter any break statement, the code beneath the subsequent case statement was also performed. So the correct script will be:
The output of the above code will be what we desired, i.e.
i equals 1If you look at the logic of the above program, there is no need to use break in the last case because the pointer will come out of the loop anyways. So, you can avoid using break statement in your last case. But if you have any confusion then use break in every case.
Now there's only one thing remaining to be understood in the above syntax -- "default". The default case is similar to the else statement. The code in the default case is executed when the expression does not match any of the case values. The following example will make this clear.
If the value of i is 5, the output will be:
i does not equal any valueA point to remember:The default case should always appear as the last case in the switch statement.
