【问题标题】:Can anyone explain the interaction of switch, while and continue?任何人都可以解释switch,while和continue的交互吗?
【发布时间】:2019-08-05 09:04:48
【问题描述】:

这里的switch语句是如何执行的?
我对continue的使用特别感兴趣。

#include <stdio.h>

int main()
{
    char ch = 'A';
    while (ch <= 'D')
    {
        switch (ch)
        {
        case 'A':
        case 'B':
            ch++;
            continue;
        case 'C':
        case 'D':
            ch++;
        }
        printf("%c", ch);
    }
}

这会输出DE,如您所见live on coliru

【问题讨论】:

  • continue; 对应while 这里
  • break 作用于最里面的fordowhileswitchcontinue 仅适用于最里面的 fordowhile。这种差异可能是一个问题。
  • 对于像这样的简短程序,一个好的开始是在调试器中运行它并遵循执行路径。在没有优化的情况下编译可能对此很有用。
  • 代码打印什么?

标签: c switch-statement continue


【解决方案1】:

简答:Continue 对应于代码中的while 循环。

最初,ch 的值是A 并且它匹配第一个案例,并且由于您的案例没有中断,一旦触发了一个案例,切换将遍历所有案例(直到中断,退出,继续,案件结束等...)。因此,它也输入 case B 并将 ch 增加到 B。由于遇到continue,它会跳过其余指令并开始while 循环的下一次迭代。

您可以在debugger 中运行它以了解这些内容。如果需要,您还可以使用老式的 printfs。

还有关于continue in switch的SO线程详细讨论

【讨论】:

    【解决方案2】:

    这里的 char 变量 'A' 是 65,'D' 是 68。如果 char 值小于或等于条件下的 while 循环将运行。然后在 switch 条件中 ch 是您之前定义的值,然后变量值与 case 的条件匹配并增加 ch 的值

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      相关资源
      最近更新 更多