switch and case

This lesson introduces switch and case statements, how and when they are used and the implementation of the final switch statement.

switch and case #

switch is a statement that allows comparing the value of an expression against multiple possible values. It is similar to but not the same as an "if, else if, else" chain. case is used for specifying which values are to be compared with switch’s expression. It is only a part of switch statement and not a statement itself.

switch takes an expression within parentheses, compares the value of that expression to the case values and executes the operations of the case that is equal to the value of the expression. Its syntax consists of a switch block that contains one or more case sections and a default section:

switch (expression) {
case value_1:
  // operations to execute if the expression is equal to value_1 
  // ...
  break;
case value_2:
  // operations to execute if the expression is equal to value_2 
  // ...
  break;

// ... other cases ...

default:
  // operations to execute if the expression is not equal to any case 
  // ...
  break;
}

The expression that switch takes is not used directly as a logical expression. It is not evaluated as “if this condition is true,” because it would be in an if statement. ...