C++ Switch

October 05, 2015 Posted by WithU Technologies
There are situations when we need to test a variable for equality against multiple values.

Though we can also do that with the help of nested if statement.

But Switch case method is an elegant way to implement this scenario.

Format:

switch (expression) {

case 1:

statement(s);

break;

case 2:

statement(s);

break;

case 3:

statement(s);

break;

default:

statement(s);

break;

}

Example:

#include <iostream>
using namespace std;

int main(){

int x=8; // integer variable initialized

switch (x){ // variable which needed to be tested with multiple values

case 2:

cout<<"This is case 3"<<endl; // If the variable value match with this case then the statement is to be displayed

break;

case 8:

cout<<"This is case 8"<<endl; // If the variable value match with this case then the statement is to be displayed

break;

case 13:

cout<<"This is case 13"<<endl; // If the variable value match with this case then the statement is to be displayed

break;

default:

cout<<"Default case"<<endl; // If the variable value does not match with any case then the statement is to be displayed

break;

  }

}



· Break statement: It will terminate the switch case statement.

· Without a break statement after each case, the statement after that continues to execute until it finds a break statement. Thus without a break statement, all the statements are executed at once even if they don’t match with the expression.

· default statement is used when the variable does not match with any of the case given and then it will execute statement under default case. It must appear at the end of the switch.