Switch

 

Switch statement is used to select one of many code blocks to be executed. This can be used as an substitute for if.. else statements and vica-versa.

 

Syntax
 

switch (variable) {
  case 1:
  //code block
  break;

  case 2:
  //code block
  break;

  default:
  //code block
}


 

What happens? The variable's value is compared with that of each case. Whichever case matches the value, that code block is executed.


 

Important Keywords

break: it breaks out of the switch block so that all the codes of other cases aren't executed.

default: This sets a standard code, which is executed if none of the other cases are executed.

 

Example:

#include <iostream>

using namespace std;

int main() 
{
  int day = 5;
  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;
}


 

Output:

Friday