Q&A: Switch Statements

Give an example of a switch statement that checks if variable num is 1, 2, or 3.

switch( num )
{
  case 1:
    // Executes if num == 1 is true
    DO_THING_A();
    break;

  case 2:
    // Executes if num == 1 is false
    // and num == 2 is true
    DO_THING_B();
    break;

  case 3:
    // Executes if num == 1 is false
    // and num == 2 is false
    // and num == 3 is true
    DO_THING_C();
    break;

  default:
    // Executes if num == 1 is false
    // and num == 2 is false
    // and num == 3 is false
    DO_THING_D();
}

A switch statement checks the value of a variable. What kind of relational statement is it equivalent to? (Greater than? Less than? Equal to? Not equal to?)

What does the default case do?

What does the break statement do?

What is flow-through?

char user_choice;
cout << "Enter choice (y/n): ";
cin >> user_choice;

switch( user_choice )
{
  case 'Y':
  case 'y':
    // Executes if user_choice == 'Y' or user_choice == 'y'
    DO_THING_A();
    break;

  case 'N':
  case 'n':
    // Executes if user_choice == 'N' or user_choice == 'n'
    DO_THING_B();
    break;

  default:
    // Executes if user_choice is not: 'Y', 'y', 'N', or 'n'
    DO_THING_C();
}

When do you need { } surrounding a case/break?

switch( user_choice )
{
  case 'W':
    {
      float withdraw;
      cout << "Enter withdraw amount: $";
      cin >> withdraw;
      balance -= withdraw;
    }
  break;

  case 'D':
    {
      float deposit;
      cout << "Enter deposit amount: $";
      cin >> deposit;
      balance += deposit;
    }
  break;
}

What data type can't be used with switch?


Author: Rachel Wil Sha Singh

Created: 2023-10-27 Fri 15:38

Validate