码迷,mamicode.com
首页 > 其他好文 > 详细

switch 与 whille相互套用

时间:2014-07-24 22:17:32      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   2014   art   

一直自以为还比较了解C++,这两天写个小工具结果出现了个bug,查了几个小时。现在才发现我这么水。

switch是C++后来推出了,目的在于提高代码结构清晰度。

但是switch与while连用时是有坑的。

bubuko.com,布布扣
 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main()
 5 {
 6     int tmp = 0;
 7     
 8     printf("while switch:\n");
 9     do{
10         scanf("%d", &tmp);
11         switch(tmp)
12         {
13             case 1:
14                 printf("case 1\n");
15                 break;
16             case 2:
17             case 3:
18                 printf("case 2, 3\n");
19                 break;
20             default:
21                 printf("default case\n");
22                 goto switch_while;
23                 break;
24         }
25         
26     }while (true);
27 
28 switch_while:
29     printf("switch while:\n");
30     
31     scanf("%d", &tmp);
32     switch(tmp)
33     {
34         case 1:
35             printf("case 1\n");
36             break;
37         case 2:
38         case 3:
39             printf("case 2, 3\n");
40             break;
41         default:
42             printf("default case\n");
43             do {
44                 scanf("%d", &tmp);
45                 if (tmp <= 1)
46                 {
47                     printf("do while <= 1\n");
48                     continue;
49                 }
50                 else if(tmp <= 3)
51                 {
52                     printf("do while 2 - 3\n");
53                     break;
54                 }
55                 else
56                 {
57                     printf("do while > 3\n");
58                 }
59             }while(0);
60             break;
61     }
62     return 0;
63 }
switch_while.cpp

switch内层嵌套while时,while的跳转符号会打乱switch的跳转。

bubuko.com,布布扣

说好的在do {} while中continue的结果直接退了出来。 这个应该是g++后来添加switch的一点bug。

而do {} while中套用switch也是有出现意外的情况的,原因也是一样由continue和break产生的符号链接冲突。

switch 与 whille相互套用,布布扣,bubuko.com

switch 与 whille相互套用

标签:style   blog   http   color   os   io   2014   art   

原文地址:http://www.cnblogs.com/karlvin/p/3866121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!