您的位置:首页 > 编程语言 > Go语言

do{...}while(0)what is it good for?

2013-10-01 17:37 477 查看
I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)

It's the only construct in C that you can use to
#define
a
multistatement operation, put a semicolon after, and still use within an
if
statement.
An example might help:
#define FOO(x) foo(x); bar(x)

if (condition)
FOO(x);
else // syntax error here
...;


Even using braces doesn't help:
#define FOO(x) { foo(x); bar(x); }


Using this in an
if
statement
would require that you omit the semicolon, which is counterintuitive:
if (condition)
FOO(x)
else
...


If you define FOO like this:
#define FOO(x) do { foo(x); bar(x); } while (0)


then the following is syntactically correct:
if (condition)
FOO(x);
else
....


It is a way to simplify error checking and avoid deep nested if's. For example:

do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: