切换案例奇怪的范围

Ric*_*bob 14 c syntax switch-statement duffs-device

回顾一些第三方C代码我遇到了类似的事情:

switch (state) {
case 0: 
    if (c=='A') { // open brace
        // code...
    break; // brace not closed!
case 1:
    // code...
    break;
    } // close brace!
case 2:
    // code...
    break;
}
Run Code Online (Sandbox Code Playgroud)

在我正在审查的代码中看起来只是一个错字,但我很惊讶它编译时没有错误.

为什么这个有效的C?
与在预期位置关闭支撑相比,对此代码执行的影响是什么?
有什么情况可以使用吗?

编辑:在示例中,我查看了存在的所有中断(如上所述) - 但如果在0或1的情况下中断,则答案还可以包括行为.

Jos*_*lor 13

它不仅有效,在实际代码中使用了类似的结构,例如Duff的Device,它是用于复制缓冲区的展开循环:

send(to, from, count)
register short *to, *from;
register count;
{
        register n = (count + 7) / 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);
        }
}
Run Code Online (Sandbox Code Playgroud)

由于switch语句实际上只是计算一个地址并跳转到它,因此很容易理解为什么它可以与其他控制结构重叠; 其他控制结构中的行也有跳转目标的地址!

在您提交的案例中,想象一下您的代码中是否有switch或者breaks.当你完成then一份if陈述的部分后,你就继续前进,所以你就会陷入困境case 2:.现在,既然你有switchbreak,它的问题是什么break可以打破的.根据MSDN页面,"The C break statement",

休息语句终止最近的封闭的执行,,开关,或同时在它出现的语句.控制传递给终止语句后面的语句.

Since the nearest enclosing do, for, switch, or while statement is your switch (notice that if is not included in that list), then if you're inside the then block, you transfer to the outside of the switch statement. What's a bit more interesting, though, is what happens if you enter case 0, but c == 'A' is false. Then the if transfers control to just after the closing brace of the then block, and you start executing the code in case 2.

  • c!='A' 案例在您解释它的方式中是有意义的 - 但从快速浏览代码的角度来看,这与直觉相去甚远! (2认同)