【问题标题】:Control Flow of switch statements without breaks无间断的 switch 语句的控制流
【发布时间】:2017-03-22 14:40:53
【问题描述】:

我对以下 switch 语句有疑问:

#include <iostream>
using namespace std;

int main()
{
    int x = 1;

    switch (x)
    {
        case 1:
            cout << "x is 1" << endl;
            //break;
        case 2:
            cout << "x is 2" << endl;
            //break;

        default:
            cout << "x is something else" << endl;
    }

}

使用 break 它可以按预期工作,但是当我注释掉中断时,输出是:

x 是 1
x 是 2
x 是别的东西

我希望输出是

x 是 1
x 是别的东西

因为 x == 1 和 case 1 被执行。如果没有中断,它还会检查不应执行的 case 2,因为 x != 2。最后默认执行。

为什么在这种情况下执行案例2?

【问题讨论】:

  • 因为它失败了 - 这就是你首先添加 breaks 的原因
  • "如果没有中断,它也会检查 case 2 ..." 不,它不检查 case 2,它只是执行代码,不再检查 case。跨度>
  • 对了,参考解释一下:en.cppreference.com/w/cpp/language/switch

标签: c++ switch-statement


【解决方案1】:

switch 运算符的case 标签不会“检查”任何内容,它们基本上是goto 标签。甚至可以写:

const int count = 12;
char dest[count], src[count] = "abracadabra", *from = src, *to = dest;
int n = 1 + (count - 1) / 8;
switch (count % 8) {
    case 0: do { *to++ = *from++;
    case 7:      *to++ = *from++;
    case 6:      *to++ = *from++;
    case 5:      *to++ = *from++;
    case 4:      *to++ = *from++;
    case 3:      *to++ = *from++;
    case 2:      *to++ = *from++;
    case 1:      *to++ = *from++;
               } while (--n > 0);
}
printf("%s\n", dest);

【讨论】:

    猜你喜欢
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多