Used to determine whether the given conditions are met, and decide which operation to perform based on the result of the determination (true or false)
- Definition:
> switch(<key>){
> case <value-1>: statements-1; break;
> case <value-2>: statements-2; break;
> default: statements-3; break;
> }
> //Execution sequence: when the key value is the same as value-1, execute statements-1 and end; if key and value-1 are not equal, but equal to value-2, execute statements-2 and end;. ..; if none are equal, execute statements-3 and end
Note: 1. There can be more than one case statement;
-
There may be no default statement, but in order to prevent error reporting due to failure to match a value equal to the key value in the case statement, try to have one (at most one) default statement;
-
There may be no break; statement after each case and default statement, which means that the switch statement will not end and continue to execute. If there is no break statement in the above example, assuming that key and value-2 are equal, then after executing statements-2 Will execute statements-3 again
- Example:
> Integer = 3
> switch (day) {
> case 0: x="Today it's Sunday"; break;
> case 1: x="Today it's Monday"; break;
> case 2: x="Today it's Tuesday"; break;
> case 3: x="Today it's Wednesday"; break;
> case 4: x="Today it's Thursday"; break;
> case 5: x="Today it's Friday"; break;
> case 6: x="Today it's Saturday"; break;
> }//final result Today it's Wednesday