Saturday, 16 September 2017

Conditional selection - switch

Conditional selection - switch

A switch statement is used instead of nested if...else statements. It is multiple branch decision statement of C++. A switch statement tests a variable with list of values for equivalence. Each value is called a case.

The case value must be a constant integer.

Structure of switch() statement

switch (expression)
{
  case value: statements...
  case value: statements...
  default : statements...
}

Individual case keyword and a semi-colon (:) is used for each constant. Switch tool is used for skipping to particular case, after jumping to that case it will execute all statements from cases beneath that case this is called as ''Fall Through''.

In the example below, for example, if the value 2 is entered, then the program will print two one something else!

int main()
{
  int i;
  cout << ''Enter an integer: '';
  cin>>i; 
  switch(i)
  {
    case 4: cout << ''four''; break;
    case 3: cout << ''three''; break;
    case 2: cout << ''two '';break;
    case 1: cout << ''one '';break;
    default: cout << ''something else!'';
  }
  return 0;
}

To avoid fall through, the break statements are necessary to exit the switch. If value 4 is entered, then in case 4 it will just print four and ends the switch.


The default label is non-compulsory, It is used for cases that are not present.

1 comment: