Switch in c++

Switch statement in c++

Multiple- selection construct that is used in  multi decision  making in an efficient way and is easy to read and understand.





Structure of Switch Statement

switch (expression)

{

   case constant1:

  group of statements 1;

  break;

  case constant2:

  group of statements 2;

  break;

  .

  .

  .

  default:

  default group of statements

}




How switch works?

switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure

Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional)

Switch Selection Structure

// counting grades assigned

int aCount, bCount, cCount, dCount, fCount;

switch (grade)

{

case ‘A’: case ‘a’:

++aCount;

case ‘B’: case ‘b’:

++bCount;

case ‘C’: case ‘c’:

++cCount;

case ‘D’: case ‘d’:

++dCount;

default:

++fCount;

}

…………

// counting grades assigned

int aCount, bCount, cCount, dCount, fCount;

switch (grade)

{

case ‘A’: case ‘a’:

++aCount;

break;

case ‘B’: case ‘b’:

++bCount;

break;

case ‘C’: case ‘c’:

++cCount;

break;

case ‘D’: case ‘d’:

++dCount;

break;

default:

++fCount;

}

Break Statement

  • break statement causes program control to move to the first statement after the selection/ repetition structure
  • Switch cases would otherwise run together

Same Behavior

Switch and if else
Switch and if else same behavior





Switch Selection Structure

Switch Selection Structure
Switch Selection Structure

 

Search within CuiTutorial

Scroll to Top