我还没有找到答案,为什么 continue in switch case 会影响 switch 外的循环,但 break 不会 "break" 循环?

I haven't found the answer to this, why continue in switch case affects the loop outside the switch but break doesn't "break" the loop?

代码如下:

#include <stdio.h>

int main ()
{
    int menu=0;
    while (menu!=3)
    {
        scanf ("%d", &menu);
        switch (menu)
        {
            case 1:
            {
                printf ("Case 1\n");
                continue;
            }

            case 2:
            {
                printf ("Case 2\n");
                break;
            }
        }
        printf ("This doesn't get printed by case 1\n");
    }

    return 0;
}

每次我把它设为 1 时,printf 都不会出现,但除此之外,它运行良好。那么 continuebreak 如何在 loop 中作用于 switch?为什么 break 不打破循环?相反,它阻止了下一个案例的处理,对吗?但是 continue 呢?需要明确的是,我实际上是在问它有何不同以及它们的实际工作方式。注意:我在 java(使用 eclipse)中也这样做过。

continue具体表示跳过当前循环中的处理,开始循环的下一次迭代(假设循环到运行的条件仍然成立)。

你的代码只有一个循环。

B(及其后代包括C++、Java或JavaScript)重载break关键字跳出switches.

因此,当您处于嵌套循环/switch 情况下时,break 关键字将应用于最内层的 switch 或循环,以更接近者为准。

这种超载是历史的偶然。 B 从复制 BCPL 开始,虽然 BCPL 后来获得了一个 endcase 关键字设计,专门用于破坏 switches,Thompson 和 Ritchie 并没有意识到这一变化,因此 B 和 C 继续他们自制的改编版break 用于此目的。

( http://port70.net/~nsz/c/c89/dmr_the_development_of_the_c_language.pdf

Not every difference between the BCPL language documented in Richards’s book [Richards79] and B was deliberate; we started from an earlier version of BCPL [Richards 67]. For example, the endcase that escapes from a BCPL switchon statement was not present in the language when we learned it in the 1960s, and so the overloading of the break keyword to escape from the B and C switch statement owes to divergent evolution rather than conscious change.

)

无论如何,在 B/C/C++ 中,break/continue 只不过是 goto 的语法糖,如果你想 break/continue 除了最内层的循环/switch,你总是可以通过使用明确的 goto:

来实现它
#include <stdio.h>

int main ()
{
    int menu=0;
    while (menu!=3)
    {
        scanf ("%d", &menu);
        switch (menu)
        {
            case 1:
            {
                printf ("Case 1\n");
                continue;
            }

            case 2:
            {
                printf ("Case 2\n");
                goto break_loop;
                //`return 0;` would work too in this case
                break; //would break out of the switch

            }
        }
        printf ("This doesn't get printed by case 1\n");
    }
break_loop:
    return 0;
}