Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty switch case in C

I'm reading through some books about C. I found the following example to switch case in C, which I try to understand ...

/* caps.c */

   #include <stdio.h>
   #include <ctype.h>

   #define SEEK 0
   #define REPLACE 1

   int main(void)
   {
     int ch, state = SEEK;
     while(( ch = getchar() ) != EOF )
     {
       switch( state )
       {
       case REPLACE:
         switch( ch )
         {
         case ' ':    //leaving case empty will go to default ???
         case '\t':
         case '\n':   state = SEEK;
                      break;
         default:     ch = tolower( ch );
                      break;
         }
         break;
       case SEEK:
         switch( ch )
         {
         case ' ':
         case '\t':
         case '\n':   break;
         default:     ch = toupper( ch );
                      state = REPLACE;
                      break;
         }
       }
       putchar( ch );
     }
     return 0;
   }

It is pretty clear to me that the mode SEEK, and then letters are Capitalized, and then mode is set to REPLACE, then letters are converted to lower. But why empty spaces trigger again SEEK mode ? Is this really the case in my comment ?

like image 840
oz123 Avatar asked Nov 28 '22 17:11

oz123


2 Answers

In this case what will happen is that the switch will enter at the appropriate case statment, so if ch=' ' at the top then run until it hits a break.

This means that if ch is one of ' ','\t' or '\n' then state will be set to SEEK.

like image 20
Dan Avatar answered Dec 01 '22 07:12

Dan


This is so-called fall-through behaviour of C switch operator. If you don't have a break at the end of a case region, control passes along to the next case label.

For example, the following snippet

int x = 5;
switch( x ) {
    case 5:
        printf( "x is five!\n" );
    case 2:
        printf( "x is two!\n" );
        break;
    default:
        printf( "I don't know about x\n" );
}

outputs

x is five!
x is two!

Be careful.

like image 171
unkulunkulu Avatar answered Dec 01 '22 08:12

unkulunkulu