C++ 继续与中断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6368141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ continue versus break
提问by eugene
Which statement will be executed after "continue" or "break" ?
"continue" 或 "break" 后将执行哪个语句?
for(int i = 0; i < count; ++i)
{
// statement1
for(int j = 0; j < count; ++j)
{
//statement2
if(someTest)
continue;
}
//statement3
}
for(int i = 0; i < count; ++i)
{
// statement1
for(int j = 0; j < count; ++j)
{
//statement2
if(someTest)
break;
}
//statement3
}
回答by Petar Ivanov
continue: ++j
and then if j < count
then statement2
otherwise statement3
继续:++j
然后如果j < count
再statement2
不然statement3
break: statement3
休息: statement3
回答by jpm
Continue jumps straight to the top of the innermost loop, where the per-iteration code and continuance check will be carried out (sections 3 and 2 of the for
loop).
Continue 直接跳转到最内层循环的顶部,在那里执行迭代代码和连续性检查(for
循环的第 3 和第 2 部分)。
Break jumps straight to immediately after the innermost loop without changing anything.
Break 直接跳到最里面的循环之后,没有任何改变。
It may be easier to think of the former jumping to the closing brace of the innermost loop while the latter jumps just beyond it.
可能更容易想到前者跳到最内层循环的右大括号而后者刚好跳过它。
回答by eugene
continue
ends the current iteration, virtually it is the same as:
continue
结束当前迭代,实际上它与以下相同:
for(int i = 0; i < count; ++i)
{
// statement1
for(int j = 0; j < count; ++j)
{
//statement2
if(someTest)
goto end_of_loop;
end_of_loop:
}
//statement3
}
break
exits the loop:
break
退出循环:
for(int i = 0; i < count; ++i)
{
// statement1
for(int j = 0; j < count; ++j)
{
//statement2
if(someTest)
goto after_loop;
}
after_loop:
//statement3
}
回答by Patrick
Continue
: It depends. The continue statement will execute the 'increment' part of the for-loop, then the 'test' part, and then decide whether to execute the next iteration or leave the loop.
So it could be statement 2 or 3.
Continue
: 这取决于。continue 语句将执行 for 循环的 'increment' 部分,然后是 'test' 部分,然后决定是执行下一次迭代还是离开循环。所以它可能是陈述 2 或 3。
Break
: statement 3.
Break
: 声明 3。
Btw, is this homework?
Btw,这是作业吗?
回答by sparkymat
statement2 will execute after the continue, given that the loop was not in the last iteration.
语句 2 将在 continue 之后执行,因为循环不在最后一次迭代中。
statement3 will execute after the break.
语句 3 将在中断后执行。
'continue' (as the name suggests) continues the loop, while skipping the rest of the statements in the current iteration.
'continue'(顾名思义)继续循环,同时跳过当前迭代中的其余语句。
'break' breaks and exits from the loop.
'break' 中断并退出循环。
回答by Adithya Surampudi
For continue, innerloop is executed with new i,j values of i,j+1
For break, innerloop is executed with new i,j values of i+1,0
对于 continue,使用新的 i,j 值 i,j+1 执行内循环
对于中断,使用新的 i,j 值 i+1,0 执行内循环
ofcourse if boundary conditions are satisfied
当然如果满足边界条件