Switch Statements in C++

As we mentioned switch statement allow you to execute one of multiple blocks of code.

Syntax:

switch(expression) {
case x:
  // code block
  break;
case y:
  // code block
  break;
default:
  // code block
}

How is works:

  • The switch expression can only evaluate once
  • The value passed into the switch expression will be compared with the value of each case.
  • If found matched then the block of code associate with that case will be executed.
  • The breakand defaultkeywords are very essential even though are optional but must be included to achieve clean and desire output. Each of them will be explain later.

Let's take an example, where we uses the weekday number to print the name of the week:

// Switch statement
#include <iostream>
using namespace std;

int main(){
  int day = 4;

  switch (day) {
    case 1:
      cout << "Monday";
      break;
    case 2:
      cout << "Tuesday";
      break;
    case 3:
      cout << "Wednesday";
      break;
    case 4:
      cout << "Thursday";
      break;
    case 5:
      cout << "Friday";
      break;
    case 6:
      cout << "Saturday";
      break;
    case 7:
      cout << "Sunday";
      break;
  }
  return 0;

  // Outputs "Thursday" (day 4)
}

The break Keyword

When C++ program reaches the breakthen the execution will stop and jump out from the switch block.

Break also stop the execution of remaining code and the testing also within that block.

When the match found, then the job is done. Simple and short.

The default Keyword

The defaultis works as last option to run when their is no condition matched or to be fulfilled.

// Switch statement
#include <iostream>
using namespace std;

int main(){
  int direction = 3;
  switch (direction) {
    case 1:
      cout << "Moving to Left...";
      break;
    case 2:
      cout << "Moving to Right...";
      break;
    default:
      cout << "Wrong Direction";
  }
  return 0;
  // Outputs "Wrong Direction"
}