这是我想做的:
{
...
if(condition)
break;
...
}
这适用于循环。我想要一个简单的代码块类似的东西。可能吗?我是否被迫使用“ goto”?
我认为break
语句的这种扩展本来是对C ++ 11的有用补充...
怎么样
do
{
...
if(condition)
break;
...
}
while (0);
我不太喜欢这种风格,但是我以前看过。如果重构是不可能的(可能是一个巨大的块,如果更改的话可能会破坏很多东西),这是一个选择。
这里是一种方式:
switch(0) {
default:
/* code */
if (cond) break;
/* code */
}
(请不要这样做)
这个:
{
// ...
if (!condition)
{
// ...
}
}
这将避免goto
跳出代码块。
这里只是一些其他可能性:
for(..)
{
continue;//next loop iteration
}
void mymethod()
{
...
return;
...
}
也许您应该为有问题的代码块创建子方法,如果您想使用goto并通过return的使用来离开代码块。
在C ++ 11中,最好的方法是使用匿名lambda函数并将break
替换为return
[&](){
...
if(condition)
return;
...
}();
请注意,[&]
通过引用捕获所有变量,如果您不使用任何变量,只需将其替换为[]
恐怕我现在正在向我释放编码神的愤怒,但是这个好看的讨厌的宏可以帮助人们比以前更轻松地做到这一点(基于@jleahy的回答:]]
//example use:
// { BREAKABLE
// ...
// if (condition)
// break;
// ...
// if (condition2)
// break;
// ...
// }
//WARNING: use only with a standalone block, to make if, try or catch block
// breakable use double braces
// if (cond) {{ BREAKABLE ... }}
// try {{ BREAKABLE ... }} catch (...) {{ BREAKABLE ... }}
#define BREAKABLE }switch(0){default:
“我想要一个简单的代码块类似的东西。”