【问题标题】:Any situation where I can't help using 'continue' within a switch statement?任何情况下我都忍不住在 switch 语句中使用“继续”?
【发布时间】:2016-04-27 13:39:19
【问题描述】:

我只是想知道为什么这么多人最终在 switch 语句中使用continue,而实际上他们根本不需要它,例如循环中的嵌套 switch 语句。假设有人写了这段 C 代码

int get_option(){...}

main(){
    int option;

    while(1){
      option = get_option();
      switch(option){
      case 0: 
          /* do something */
          continue;  
      case 1:
          /* do something */
          break;
      case 2:
          /* do something */
          continue;  
      default:
}

在这里,以continue 结束一个案例似乎与break 产生完全相同的结果。在我看来,结束 switch 语句的正式方法是使用break,因为无论语句是否嵌套在循环中,您始终可以使用它来结束一个案例。在这里使用continue 对我来说似乎很糟糕。

如果你能想到我在 switch 语句中真正需要continue 的任何情况,请给我一个想法。

【问题讨论】:

  • 这个问题有点宽泛,但是如果在某些情况下您不想在 switch 语句之后执行 语句怎么办?这意味着continue 是正确的路径,因为break 会导致切换后的部分也执行。
  • 如果 switch 语句不是循环中的最后一件事,它会有所不同,因为 continue 会跳回循环的顶部。
  • continueswitch 语句无关。它作用于循环!
  • 我不太明白为什么您认为 continue 会放错位置或 看起来很糟糕。毕竟,这正是它的目的?

标签: c switch-statement


【解决方案1】:

用于决定是否应该执行switch语句之后的某些语句。这是一个例子:

#include <stdio.h>
#include <ctype.h>

int get_option(void)
{
    int num;
    do{
        num = getchar();
    } while(isspace(num));
    if(isdigit(num))
        return num - '0';
    else
        return -1;
}

int main(void)
{
    int option;
    while(1){
        option = get_option();
        switch(option){
            case 0: 
                puts("You've entered 0");
                continue; // <--- continue; gives you nothing
            case 1:
                puts("You've entered 1");
                break; // <--- break; gives you "You've entered an odd number"
            case 2:
                puts("You've entered 2");
                continue;
            default:
                puts("Input out of range!");
                continue;
        }
        puts("You've entered an odd number"); // <--- Notice this line
    }
}

输入输出:

0
You've entered 0
1
You've entered 1
You've entered an odd number
2
You've entered 2
3
Input out of range!

【讨论】:

    【解决方案2】:
    int get_option(){...}
    
    main(){
      int option;
      while(1){
        option = get_option();
        switch(option){
          case 0: 
            /* do something */
            continue;
          case 1:
            /* do something */
            break;
          case 2:
            /* do something */
            continue;  
          default:
        }
        /* this is executed if (option!=0)&&(option!=2)
           otherwise skipped */
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多