c++ - 在 switch 语句中使用 continue

标签 c++ c switch-statement break continue

我想从 switch 语句的中间跳转到下面代码中的循环语句:

while (something = get_something())
{
    switch (something)
    {
    case A:
    case B:
        break;
    default:
        // get another something and try again
        continue;
    }
    // do something for a handled something
    do_something();
}

这是使用 continue 的有效方式吗? switch 语句是否会忽略 continue 语句? C 和 C++ 在这里的行为是否有所不同?

最佳答案

没关系,continue语句与封闭循环有关,你的代码应该相当于(避免这样的跳转语句):

while (something = get_something()) {
    if (something == A || something == B)
        do_something();
}

但是,如果您希望 break 退出循环,正如您的评论所建议的那样(它总是用另一个东西再次尝试,直到它评估为 false),您将需要一个不同的结构。

例如:

do {
    something = get_something();
} while (!(something == A || something == B));
do_something();

关于c++ - 在 switch 语句中使用 continue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146763/

相关文章:

c++ - 如何在节点类中实现节点引用

c++ - 函数内部的函数声明是否有用?

c - 如何防止客户端使用低于 v1.2 的 TLS 进行连接?

c# - Arduino 用 Visual C# 制作的软件无法正常工作

c - 在从未更改的枚举上切换大小写

javascript - 有没有更好的方法在 JavaScript 中编写这个开关?

jquery - 使用 Jquery 的持久样式表切换器

c++ - 在 C++ 中在内存中创建大流

c++ - 调用模板函数时出现歧义

c++ - 递归模板类型声明