Tuesday, April 5, 2011

The Switch Statement; Break; Continue In C

The switch statement can be used to replace the multi-way test we used in the last example.  When the tests are like this:
if( c == 'a' ) ...
       else if( c == 'b' ) ...
       else if( c == 'c' ) ...
       else ...
testing a value against a series of constants, the switch statement is often clearer and usually gives better code.  Use it like this:
switch( c ) {

       case 'a':
               aflag++;
               break;
       case 'b':
               bflag++;
               break;
       case 'c':
               cflag++;
               break;
       default:
               printf("%c?\n", c);
               break;
       }
The case statements label the various actions we want; default gets done if none of the other cases are satisfied.  (A default is optional; if it isn't there, and none of the cases match, you just fall out the bottom.)
The break statement in this example is new.  It is there because the cases are just labels, and after you do one of them, you fall through to the next unless you take some explicit action to escape.  This is a mixed blessing. On the positive side, you can have multiple cases on a single statement; we might want to allow both upper and lower
case 'a':  case 'A':    ...

       case 'b':  case 'B':    ...
        etc.
But what if we just want to get out after doing case `a' ? We could get out of a case of the switch with a label and a goto, but this is really ugly.  The break statement lets us exit without either goto or label.
switch( c ) {

       case 'a':
               aflag++;
               break;
       case 'b':
               bflag++;
               break;
        ...
       }
       /* the break statements get us here directly */
The break statement also works in for and while statements; it causes an immediate exit from the loop.The continue statement works only inside for's and while's; it causes the next iteration of the loop to be started.  This means it goes to the increment part of the for and the test part of the while We could have used a continue in our example to get on with the next iteration of the for, but it seems clearer to use break instead.

0 comments:

Post a Comment

Breaking News
Loading...
Quick Message
Press Esc to close
Copyright © 2013 Crack o Hack & tweak STORE All Right Reserved