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 ?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With