switch() case:

The switch case statement is a better way of writing a program when a series of if elses occurs.

The general format for this is,

         switch ( expression ) {
               case  value1:
                       program statement;
                       program statement;
                       ......
                       break;
               case  valuen:
                       program statement;
                       .......
                       break;
               default:
                       .......
                       .......
                       break;
        }
 The keyword break must be included at the end of each case statement. 
 The default clause is optional, and is executed if the cases are not met. 
 The  right brace at the end signifies the end of the case selections.

Rules for switch statement

  • values for 'case' must be integer or character constants
  • The order of the 'case' statements is unimportant
  • The default clause may occur first (convention places it last)
  • You cannot use expressions or ranges
Back