是否有理由拥有以下代码:
do {
// a lot of code that only needs to be run once
} while (FALSE);
当代码没有定义宏时?我知道这对于宏来说是一个技巧,但在普通代码中是否有理由这样做?
答案 0 :(得分:10)
好吧,如果您出于某种原因需要,可以使用break;
(或continue
)关键字提前退出。那会有点难看。我真的宁愿看到它进入自己的例程,通过return;
语句实现提前退出。
答案 1 :(得分:3)
原因之一就是如果你想在某个时候爆发。
即
do
{
//some code that should always execute...
if ( condition )
{
//do some stuff
break;
}
//some code that should execute if condition is not true
if ( condition2 )
{
//do some more stuff
break;
}
//further code that should not execute if condition or condition2 are true
}
while(false);
在某些情况下,如果按上述方式编写,结果代码会更清晰/更容易理解。
答案 2 :(得分:2)
这样的构造用作一种goto
,能够在循环结束后使用break
语句跳转。
答案 3 :(得分:2)
我不会这样做但是:
我看起来不仅仅是大括号
int main()
{
{
std::ifstream file("Data");
// DO STUFF
} // Data now closed.
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// We can re-use data here as it was closed.
std::ofstream file2("Data");
// DO STUFF
}
一个不守规矩的维护者可能会看到括号并思考 什么哎呀并删除它们
int main()
{
std::ifstream file("Data");
// DO STUFF
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// FAIL. data is still open from before.
std::ofstream file2("Data");
// DO STUFF
}
我认为使用while tick至少会让syou考虑它(尽管一个不守规矩的维护者仍然可以删除它)。
int main()
{
do
{
std::ifstream file("Data");
// DO STUFF
} while (false);
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// We can re-use data here as it was closed.
std::ofstream file2("Data");
// DO STUFF
}
答案 4 :(得分:1)
没有理由在编译时编写一个已知的循环来执行一次。
这样做是为了假装goto
被写为break
,这是虐待。
编辑:
我刚刚意识到我对编译时知识的断言是错误的:我想你可能会做一些复杂的条件#defines,这可能意味着,在一个构建配置的编译时,它已知执行一次,但是对于不同的构建配置,它会被执行多次。
#ifdef SOMETHING
#define CONDITION (--x)
#else
#define CONDITION 0
#endif
...
int x = 5
do{
...
} while(CONDITION)
然而,我的主张的精神仍然存在。
答案 5 :(得分:0)
它可用于实现类似于goto
语句的行为,或者说跳转行为!
见:
do
{
if (doSomething() != 0) break; //jump
if (doSomethingElse() != 0) break; //jump
...
if (doSomethingElseNew() != 0) break; //jump
} while(false);
//if any of the break encountered, execution can continue from here, just after the do-while block!
// statement1
// statement2
// statement3
// so on