c - 开关盒跌落场景

标签 c switch-statement fall-through

所以我遇到了一个竞争性问题(询问输出)如下:

#include <stdio.h>
int main()
{
    int i = 0;
    for(i = 0; i < 20; i++)
    {
        switch(i)
        {
            case 0: i+=5;
            case 1: i+=2;
            case 5: i+=5;
            default: i+= 4;
            break;
        }
        printf("%d ", i);
    }
    return 0;
}

输出为 16, 21。虽然我知道 switch case 是如何工作的,但我无法向自己解释这个 fall through 是如何工作的。为什么要添加默认值? K&R C 书不是说只有在所有情况都不匹配时才执行默认设置吗?
谢谢。

最佳答案

如果没有其他情况匹配,默认情况只会从 switch 语句跳转到。其中一个匹配后,代码将执行,就好像所有 case 语句都不存在一样,除非它遇到了 break。所以 default 案例并没有像您预期的那样“跳过”。

K & R 对此有点不清楚,你指的那行似乎是:

If a case matches the expression value, execution starts at that case. All case expressions must be different. The case labeled default is executed if none of the other cases are satisfied

但这是在谈论 switch 语句如何分支。 Fallthrough 行为在下一页:

Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape.

这不取决于是否有 default 情况。

C 标准更清晰:

A switch statement causes control to jump to, into, or past the statement that is the switch body , depending on the value of a controlling expression ... If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. Otherwise, if there is a default label, control jumps to the labeled statement.

一旦控制跳转,casedefault 标签就不再重要了。

关于c - 开关盒跌落场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585342/

相关文章:

c# - 检查命令行参数的输入值

python - Python 字典中 switch/case 替换失败

c - scanf 如何处理空白区域?

c - Valgrind 报告

ios - 是否有不同的实现来避免我的长 switch 语句?

go - 在 Golang 中失败

R:如何使 switch 语句失效

c - Valgrind 说 "definitely leak"但它是吗?

c - if 条件在运行时执行的顺序

c++ - 将用户输入验证为 int 时陷入无限循环