做{...}而(0) - 什么是好? [英] do { ... } while (0) — what is it good for?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/154136/why-are-there-sometimes-meaningless-do-while-and-if-else-statements-in-c-c-macr\">Why在那里,有时毫无意义的do / while和如果C / else语句/ C ++宏?
我已经看到,现在超过10年的前pression。我一直在试图想这是很好的。因为我看到它主要是在#define语句,我认为这是很好的内部范围变量声明和使用中断(而不是goto方法的。)
I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)
这是好做别的事情?你使用它?
Is it good for anything else? Do you use it?
推荐答案
这是唯一的构建用C,你可以用它来的#define
A多语句操作,把一个分号之后,仍然是如果
语句中使用。一个例子可以帮助:
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
...
如果你定义FOO这样的:
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
....
这篇关于做{...}而(0) - 什么是好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!