c语言中的switch语句使用

默认分类 · 2011-02-15

今天编程用switch发现一个问题,算了,先贴源程序再说问题吧。

 1 #include <stdio.h>
 2 int main(int argc, char * argv[])
 3 {
 4   int t = 0;
 5   switch (  t  )
 6     {
 7     case -1 :
 8       printf ( "test\n" );
 9     case 0:
10       printf ( "the postgresql server has been started by myself\n" );
11     default:
12       printf ( "the postgresql server can not be started ,please install it firse\n" );
13       exit ( 0 );
14     }
15 
16 }
17 

编译运行,其输出结果如下:

the postgresql server has been started by myself

the postgresql server can not be started ,please install it firse

但是,大家知道我想要的不是这个结果,不是这个结果啊

那问题出在哪儿呢?我找了半天,似乎解决了,更改后的源程序如下

 1 #include <stdio.h>
 2 int main(int argc, char * argv[])
 3 {
 4   int t = 0;
 5   switch (  t  )
 6     {
 7     case -1 :
 8       printf ( "test\n" );break;
 9     case 0:
10       printf ( "the postgresql server has been started by myself\n" );break;
11     default:
12       printf ( "the postgresql server can not be started ,please install it firse\n" );
13       exit ( 0 );
14     }
15 
16 }
17 

更改后编译运行结果如下

the postgresql server has been started by myself

嗯,这才是我要的结果

那两段源程序的区别在哪儿呢?

在于我加了break。

编程 c语言
Theme Jasmine by Kent Liao