我正在编写一些看起来像这样的代码:
I'm writing some code that looks like this:
while(true) {
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
break; // **HERE, I want to break out of the loop itself**
}
}
有没有直接的方法可以做到这一点?
Is there any direct way to do that?
我知道我可以使用一个标志,并通过在 switch 之后放置一个条件中断来中断循环.我只是想知道 C++ 是否已经为此提供了一些构造.
I know I can use a flag, and break from the loop by putting a conditional break just after the switch. I just want to know if C++ has some construct for this already.
无论语言或所需功能如何,以下代码都应被视为不良形式:
The following code should be considered bad form, regardless of language or desired functionality:
while( true ) {
}
while( true )
循环是糟糕的形式,因为它:
The while( true )
loop is poor form because it:
while(true)
来表示非无限循环,那么当循环实际上没有终止条件时,我们就失去了进行简洁交流的能力.(可以说,这已经发生了,所以这一点没有实际意义.)while(true)
for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)以下代码是更好的形式:
The following code is better form:
while( isValidState() ) {
execute();
}
bool isValidState() {
return msg->state != DONE;
}
没有标志.没有goto
.没有例外.容易改变.易于阅读.易于修复.另外代码:
No flag. No goto
. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:
第二点很重要.在不知道代码如何工作的情况下,如果有人让我让主循环让其他线程(或进程)有一些 CPU 时间,我会想到两种解决方案:
The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:
随时插入停顿:
while( isValidState() ) {
execute();
sleep();
}
覆盖执行:
void execute() {
super->execute();
sleep();
}
此代码比带有嵌入式 switch
的循环更简单(因此更易于阅读).isValidState
方法应该只确定循环是否应该继续.方法的主力应该抽象为 execute
方法,它允许子类覆盖默认行为(使用嵌入式 switch
和 goto代码>).
This code is simpler (thus easier to read) than a loop with an embedded switch
. The isValidState
method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute
method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch
and goto
).
对比 StackOverflow 上发布的以下答案(针对 Python 问题):
Contrast the following answer (to a Python question) that was posted on StackOverflow:
代码
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
对比:
代码
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
在这里,while True
会导致误导和过于复杂的代码.
Here, while True
results in misleading and overly complex code.
这篇关于如何从交换机内部跳出循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!