FANDOM


A switch statement (or case statement) compares an expression with a series of values in a specified order and takes the action associated with the matching value. A default action can be specified, which will be taken if no match is found. In some languages, the expression must result in a scalar value, and the cases must be constant expressions.

Typical syntax is:

switch (expression) {
    case value1:
        //take action 1
        break;
    case value2:
        //take action 2
        break;
    case value3:
        //take action 3
        break;
    default: take default action
}

Switch statements can be thought of as a terser way of expressing a series of cascading if-then-else statements. In this way, they provide a natural and readable way for a programmer to express this common decision-making behaviour.


Break statement Edit

The break statement prevents other blocks from being executed. In the following piece of code both blocks get executed due to the lack of a break.

int i = 2;

switch (i) {
    case 2:
        print "this is a 2";
    case 3:
        print "this is a 3";
}

It's worth noting that the default case does not have a break. this is because it would be pointless as the statement would finish at this stage anyway.

As a matter of best practice it's probably not a good idea to leave out the breaks. However it is a possible cause of bugs in a switch statement.

Alternative Approaches Edit

It is common for switch statements to grow over time, as more options and possible actions become apparent. Such statements can become unwieldy and hard to maintain. In this case, the Strategy Pattern may provide an appropriate replacement.

Control structures
If statement - Switch statement - While loop - For loop - Foreach loop - Do while loop

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.