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 ?
This is so-called fall-through behaviour of C
switchoperator. If you don’t have abreakat the end of acaseregion, control passes along to the nextcaselabel.For example, the following snippet
outputs
Be careful.