【问题标题】:How does switch behave as a goto? [closed]switch 如何表现得像 goto? [关闭]
【发布时间】:2014-05-12 05:36:45
【问题描述】:

我试图了解switch 在 C 中的工作原理,在浏览了一些关于 SO 的答案后,我摸索了以下关于 SO 的答案:-

基本上,switch 的作用就像是转到相应的标签——中间的语句不会被执行。变量定义(实际上发生在编译时)确实会发生,但如果它们包含初始化,也会被跳过。

How does switch statement work?

任何人都可以解释一下这个声明的含义或提供更多关于switch工作的见解。
`

【问题讨论】:

  • 您在发布的链接中遇到的具体问题是什么?接受的答案以及您突出显示的陈述似乎很清楚。
  • 您在寻找如何使用它的解释吗?为了解释它是如何在内部实现的?对于它与 goto 语句的相似性的哲学思考?
  • 我无法理解这个特定问题如何回答链接中的问题。
  • 一个代码示例对于证明这句话的真实性非常有用。
  • @ps06756,您链接的帖子的其他答案中有代码示例。

标签: c switch-statement goto


【解决方案1】:

这是一个switch 语句的示例,直接从this answer 复制而来。

#include <stdio.h>

int main(){
    int expr = 1;
    switch (expr)
    {
        int i = 4;
        f(i);
        case 0:
        i = 17;
        /* falls through into default code */
        default:
        printf("%d\n", i);
    }
}

这是一个等效的代码示例,用goto编写。

#include <stdio.h>

int main(){
    int expr = 1;
    if (expr == 0) goto label0;
    else goto label1;

    int i = 4;
    f(i);
    label0:
    i = 17;

    label1:
    printf("%d\n", i);
}

请注意,在这两种情况下,当expr 初始化为1 时,初始化语句int i = 4 未执行,因此i 未初始化。但是,i 已定义,正如问题中的引用所提到的那样。

【讨论】:

    【解决方案2】:

    无开关:

      if(1 == x)
         goto LABEL_A;
      else if(2 == x)
         goto LABEL_B;
      else if(10 == x)
         goto LABEL_C;
      else
         goto LABEL_D;
    
    LABEL_A:
      /* Do A */;
      goto BREAK;
    
    LABEL_B:
      /* Do B */;
      goto BREAK;
    
    LABEL_C:
      /* Do C */;
      goto BREAK;
    
    LABEL_D:
      /* Do D */;
      goto BREAK;
    
    BREAK:
    

    带开关:

    switch(x)
      {
      case 1:
         /* Do A */;
         break;
    
      case 2:
         /* Do B */;
         break;
    
      case 10:
         /* Do C */;
         break;
    
      default:
         /* Do D */;
         break;
      }
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2014-12-01
      • 1970-01-01
      • 2015-02-08
      • 2010-10-23
      相关资源
      最近更新 更多