Sunday, September 9, 2012

Understanding The Switch Statement

Basic Syntax:

switch(some-expression){
case some-constant1:
/* some code*/
break;


case some-constant2:
/* some code*/
break;


default:
/*some code*/
break;
}

Now important points worth noting are:

  1. some-expression in the switch(some-expression) can be an expression, a constant or a variable
  2. In the cases within switch construct, some-constant are constant integer values. Floats and expressions are not allowed here
  3. break; is optional
  4. default case is also optional
Interesting cases arise when break; are not used. Look at the following example:



switch(1*3-1){
case 1:
printf("\nThis is case 1.");


case 2:
printf("\nThis is case 2.");


case 3:
printf("\nThis is case 3.");

default:
printf("\nThis is default case.");
}

If you run this the output is:

This is case 2.
This is case 3.
This is default case.

So you can see that switch goes directly to the case indicated by the value of some-expression and then keeps on executing statements until a break; is encountered or until the end of the construct.

PS 1: Compiler used is TurboC
PS 2: Corrections/Suggestions/Comments are welcome.

No comments:

Post a Comment