do{}while(0);

来源:互联网 发布:网络对实体店的冲击 编辑:程序博客网 时间:2024/05/16 17:38


第一次在 redis 的 dict 源码中看到这种用法。

1,用在宏中,come from stackoverflow

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within anif 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    ....

2,

用来做错误检查

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);

0 0
原创粉丝点击