Switch-Case in C++

Switch-case in C++

Switch case allows you to select the required block of code  from an available block of codes

Execution flow

  • First, the compiler searches the switch expression, top to bottom from available case labels
  • If a case label is matched with the switch expression then body under case label gets executed, then all other case labels get skipped
  • If no case label is matched with switch expression body under default get executed
  • Remember, only one case label gets executed from available case labels,  i.e  case label that is matched with the switch expression
Switch Case in C++

C ++ program to demonstrate switch case

main()
{
char op;
float num1, num2;

cout << "Enter operator either + or - or * or /: ";
cin >> op;

cout << "Enter two operands: ";
cin >> num1 >> num2;

switch(op)
{
case '+':
cout << num1+num2;
break;

case '-':
cout << num1-num2;
break;

case '*':
cout << num1*num2;
break;

case '/':
cout << num1/num2;
break;

default:
//if case label not available
cout << "select valid choice";
break;
}

}

Output

Enter operator either + or - or * or divide : +
Enter two operands:
8
3
8+3 = 11

Points to Remember

Using break is optional but  it results in the execution of  all case labels from matched case label

main()
{

switch(2)
{

case 1:
cout<<"Laxmi\n";

case 2:
cout<<"trishaank\n";//matched case label

case 3:
cout<<"rishvik\n";

deafult:
cout<<"vijay";

}

}

O/P

trishaank
rishvik
vijay

Default can be placed anywhere in the switch, but it is executed only if matching case label is not available

main()
{

switch(2)
{

case 1:
cout<<"Laxmi\n";
break;

case 2:
cout<<"trishaank\n";//matched case label
break;

deafult:
cout<<"vijay";
break;

case 3:
cout<<"rishvik\n";

}
}

O/P

trishaank

Duplicate case labels are not allowed

main()
{

switch(2)
{

case 1:
cout<<"Laxmi\n";
break;

case 1://error:ambiguos case label
cout<<"trishaank\n";//matched case label
break;

deafult:
cout<<"vijay";
break;

case 3:
cout<<"rishvik\n";

}
}

Case labels can be constants or constant expressions but not variables

main()
{

switch(2)
{

case 1:
cout<<"Laxmi\n";
break;

case 1+1://same as case 2
cout<<"trishaank\n";//matched case label
break;

default:
cout<<"Vijay";
break;

case 1+1+1:
cout<<"rishvik\n";

}
}

O/P

trishaank

Other than float any data type is valid for the case label

main()
{

switch(2.1)
{

case 2.1:
cout<<"Laxmi\n";
break;

case 2.2:
cout<<"trishaank\n";
break;

deafult:
cout<<"vijay";
break;

case 2.3:
cout<<"rishvik\n";

}
}

O/P

complier error

One comment on “Switch-Case in C++”