Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 855
Pietro Avatar asked Sep 07 '12 08:09

Pietro


4 Answers

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 []

like image 50
Edwin Rodríguez Avatar answered Oct 12 '22 14:10

Edwin Rodríguez


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.

like image 37
Luchian Grigore Avatar answered Oct 12 '22 14:10

Luchian Grigore


Here's one way:

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

(please never do this)

like image 27
jleahy Avatar answered Oct 12 '22 14:10

jleahy


This one:

{
    // ...

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

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

like image 5
Charan Pai Avatar answered Oct 12 '22 14:10

Charan Pai