“do while”和“goto out”在这些区域有所不同:
1。局部变量初始化
void foo(bool t = false)
{
if (t)
{
goto DONE;
}
int a = 10; // error : Goto bypass local variable's initialization
cout << "a=" << a << "\n";
DONE:
}
在do ... while(0)块中初始化就地局部变量是很好的。
void bar(bool t = false)
{
do{
if (t)
{
break;
}
int a = 10; // fine
cout << "a=" << a << "\n";
} while (0);
}
2宏的差异。 “尽管”稍微好一点。宏中的“goto done”并非如此。 如果退出代码是比较复杂的,我们看到这样的:
err = some_func(...);
if (err)
{
register_err(err, __LINE__, __FUNC__);
#if defined (_DEBUG)
do_some_debug(err)
#endif
break;
}
,并再次写这个代码,并再次,你可能把它们放入一个宏。
#define QUIT_IF(err) \
if (err) \
{ \
register_err(err, __LINE__, __FUNC__); \
DO_SOME_DEBUG(err) \
break; // awful to put break in macro, but even worse to put "goto DONE" in macro. \
}
并成为代码:
do
{
initial();
do
{
err = do_step1();
QUIT_IF(err);
err = do_step2();
QUIT_IF(err);
err = do_step3();
QUIT_IF(err);
....
} while (0);
if (err) { // harder for "goto DONE" to get here while still using macro.
err = do_something_else();
}
QUIT_IF(err);
.....
} while (0);
3.do ......而(0)处理不同级别相同的宏退出的。代码如上所示。转到...宏不是这种情况,因为你需要不同级别的不同标签。
通过这样说,我不喜欢他们两个。我宁愿使用异常方法。如果不允许异常,那么我使用“do ... while(0)”,因为整个块缩进了,实际上比“goto DONE”风格更容易阅读。
使用while(1)使得读取代码的人期望它运行“无限”......为什么不使用do {} while(0)? – 2009-07-02 09:39:02
@Tal Pressman - 为什么会有所不同? – 2009-07-02 09:40:51
@Earwicker,用这个选项很明显它至少运行一次,并且它不会再运行,因为条件是“while(0)”。混淆的“while(1)”没有出现。 – 2009-07-02 09:44:55