Using continue in a switch statement(在 switch 语句中使用 continue)
问题描述
我想从 switch 语句的中间跳转到下面代码中的循环语句:
I want to jump from the middle of a switch statement, to the loop statement in the following code:
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++ 在这里的行为是否有所不同?
Is this a valid way to use continue? Are continue statements ignored by switch statements? Do C and C++ differ on their behaviour here?
推荐答案
没关系,continue语句与封闭循环有关,你的代码应该相当于(避免这样的跳转语句):
It's fine, the continue statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):
while (something = get_something()) {
if (something == A || something == B)
do_something();
}
但是,如果您希望 break 退出循环,正如您的评论所建议的那样(它总是用另一个东西再次尝试,直到它评估为 false),您将需要一个不同的结构.
But if you expect break to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.
例如:
do {
something = get_something();
} while (!(something == A || something == B));
do_something();
这篇关于在 switch 语句中使用 continue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 switch 语句中使用 continue
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
