Name

switch statement — Multibranch selection statement

Synopsis

               statement := switch ( condition ) statement
               condition ::= expression | type-specifier-seq 
               declarator = assignment-expr
            

The switch statement evaluates condition and saves the value. It compares the value to each case label in statement (which is typically a compound statement). The statements that follow the matching case label are executed. If no case label matches, the statements following the default label are executed. If there is no default, execution continues with the statement following the end of the switch statement.

All case labels in statement must be unique. Use the break statement to exit the switch statement at the end of each case.

Example

switch(c) {
case '+':
  z = add(x, y);
  break;
default:
  z = noop(  );
  break;
};

See Also

break, case, declarator, default, expression, if, statement, type, Chapter 4

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.