Switch statements

Table of Contents


1. Switch statements

Switch statements are a special type of branching mechanism that \underline*only* checks if the value of a variable is equal to one of several values. Switch statements can be useful when implementing a menu in a program, or something else where you only have a few, finite, discrete options.

In C++, switch statements only work with primitive data types, like integers and chars - not strings.

switch ( VARIABLE )
{
case VALUE1:
  // Do thing
break;

case VALUE2:
  // Do thing
break;

default:
  // Default code
}

With a switch statement, each case is one equivalence expression. The default case is executed if none of the previous cases are.

  • = case VALUE1: = is equivalent to = if (VARIABLE == VALUE1) =
  • = case VALUE2: = is equivalent to = else if (VARIABLE == VALUE2) =
  • = case default: = is equivalent to = else =

The default case is not required, just like how the else clause is not required in an if statement.

The break; statement

The end of each case should have a break; statement at the end. If the break is not there, then it will continue executing each subsequent case's code until it does hit a break.

This behavior is "flow-through", and it can be used as a feature if it matches the logic you want to write.

Example: Perhaps you are implementing a calculator, and want to get an option from the user: (A)dd, (S)ubtract, (M)ultiply, or (D)ivide. You could store their choice in a char variable called operation and then use the switch statement to decide what kind of computation to do:

switch ( operation )
{
case 'A': // if ( opreation == 'A' )
  result = num1 + num2;
break;

case 'S': // else if ( operation == 'S' )
  result = num1 - num2;
break;

case 'M': // else if ( operation == 'M' )
  result = num1 * num2;
break;

case 'D': // else if ( operation == 'D' )
  result = num1 / num2;
break;
}

cout << "Result: " << result << endl;

Author: Rachel Wil Sha Singh

Created: 2023-10-23 Mon 15:48

Validate