Switch statement in C++

Switch statement in C++

2 min read

SWITCH STATEMENT

C++ provide a multiple-branch selection statement known as switch.It tests the value of an expression/condition against a list of integers or character constant.On matching associated statements are executed.

Syntax:-

switch(expression)
{
 case constant1:statement1;
              break;
 case constant2:statement2;
              break;
 case constant3:statement3;
              break;
 :
 :
 :
 case constant n:statement n; 
               break;
       default : statement;
}

The expression is evaluated and its values are matched against the values of constants specified in case statements. When a match is found, the statement associated is executed until the break statement is encountered. When a break is encountered control comes out of switch’s body.

Now what happens if there is no break in a case?

Then there will be a condition of fall-through. Fall-through is a situation when break is missing in a case statement. At that time the control continues on the next case statements.

Now if there is no break in any case?

Then all the statements are executed even the default one’s, and control comes out of switch.

Let’s take an example to understand.

int main()
{
  int dow;
  cout<<”enter number of week’s day(1-7)\n”;
  cin>>dow;
  switch(dow)
{
  case 1: cout<<”\n monday”;
        break;
  case 2: cout<<”\n tuesday”;
        break;
  case 3: cout<<”\n wednesday”;
        break;
  case 4: cout<<”\n thursday”;
        break;
  case 5: cout<<”\n friday”;
        break;
  case 6: cout<<”\n saturday”;
        break;
case 7: cout<<”\n sunday”;
        break;
}
  return 0;
}

OUTPUT

Enter number of week’s day(1-7)
5
friday

Comparison between switch and if-else

if-elseswitch
The if-else is more versatile.It can handle ranges of values.Switch cannot handle ranges, Each switch case label must be a single value.
The if-else statements can handle floating point tests also.Switch cannot handle floating point tests.
If-else is less efficient as compared to switch.Switch is more efficient in terms of code used in a situation that supports nature of switch.
For comparison of variables, if-else is more efficient.The switch case label value must be a constant.
The if statement evaluates an expression repeatedly until it finds a match.A switch statements evaluates the expression code only once.
Difference between if-else and Switch Statements

IMPORTANT

  1. The ANSI Standard specifies that a switch can have upto 257 case statements.
  2. A switch can only work for equality comparisons.
  3. No two case labels in a switch can have identical values. But allowed in case of nested switch(switch inside switch).
  4. It can only work for characters and integers.
  5. A switch statement is more efficient than nested if-else.
Choose your Reaction!
Leave a Comment