How to jump out of a C++ code block?

大兔子大兔子 提交于 2019-11-30 03:11:16

问题


This is what I would like to do:

{
    ...
    if(condition)
        break;
    ...
}

This works for a loop. I would like something similar for a simple block of code. Is it possible?
Am I forced to use a "goto"?


I think such an extension of the break statement would have been a useful addition to C++11...


回答1:


How about

do
{
    ...
    if(condition)
        break;
    ...
}
while (0);

I don't particularly like this style but I've seen it before. If refactoring is out of the question (could be for a massive block that can break a lot of stuff if changed), this is an option.




回答2:


This one:

{
    // ...

    if (!condition)
    {
        // ...
    }
}

This will avoid goto to jump out of a block of code.




回答3:


Here's one way:

switch(0) {
default:
    /* code */
    if (cond) break;
    /* code */
}

(please never do this)




回答4:


Here just some additional possibilities:

for(..)
{
    continue;//next loop iteration
}

void mymethod()
{
    ...
    return;
    ...
}

Probably you should create sub-methods for the problematic block of code were you wanted to use goto and leave the block of code by the usage of return.




回答5:


In C++11 the best way to achieve this is use a anonymous lambda function and replacing break with return

[&](){
    ...
    if(condition)
        return;
    ...
 }();

Note that [&] captures all variables by reference, if you don't use any just replace it with []




回答6:


"I would like something similar for a simple block of code."

Use return after a condition is met, and return control back to the caller.

void MyWorkerClass::doWork(Item & workItem) {
    // ...
    if(noMoreWorkToDo)
        return;
    // ...
}


来源:https://stackoverflow.com/questions/12314619/how-to-jump-out-of-a-c-code-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!