C中的空开关盒

Oz1*_*123 4 c switch-statement

我正在阅读一些关于C的书.我发现以下示例在C中切换案例,我试图理解......

/* 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;
   }
Run Code Online (Sandbox Code Playgroud)

我很清楚,模式SEEK,然后字母是大写,然后模式设置为REPLACE,然后字母转换为更低.但为什么空格会再次触发SEEK模式?这是我的评论中的情况吗?

unk*_*ulu 13

这就是C switch运算符的所谓直通行为.如果区域break末尾没有a case,则控制传递到下一个case标签.

例如,以下代码段

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" );
}
Run Code Online (Sandbox Code Playgroud)

输出

x is five!
x is two!
Run Code Online (Sandbox Code Playgroud)

小心.