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...
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 []
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.
Here's one way:
switch(0) {
default:
/* code */
if (cond) break;
/* code */
}
(please never do this)
This one:
{
// ...
if (!condition)
{
// ...
}
}
This will avoid goto
to jump out of a block of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With