做{}而(0)与如(1){}中的宏 [英] do { } while(0) vs. if (1) { } in macros

查看:95
本文介绍了做{}而(0)与如(1){}中的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/154136/why-are-there-sometimes-meaningless-do-while-and-if-else-statements-in-c-c-mac\">Why在那里,有时毫无意义的do / while和如果C / else语句/ C ++宏?

当一个人需要preprocessor宏内执行多个语句,它通常是这样写

When one needs to execute multiple statements within preprocessor macro, it's usually written like

#define X(a) do { f1(a); f2(a); } while(0)

所以,当这宏内部使用前pressions这样的:

so when this macro is used inside expressions like:

if (...)
    X(a);

它不会被搞砸了。

it would not be messed up.

现在的问题是:无论我见过这样的前pression,它总是做{...}而(0); 。是否有任何理由preFER这样的概念了(在我看来更清晰的)如果(1){...} ?还是我错了,我的意见,他们都同样受欢迎?

The question is: wherever I've seen such expression, it's always do { ... } while(0);. Is there any reason to prefer such notion over (in my opinion more clear one) if (1) { ... }? Or am I wrong in my observations and they are equally popular?

推荐答案

不,你没看错。

实际上,有一个很好的理由:

There's actually a nice reason:

#define my_code if (1) { ... }

if (1)
    my_code;

问题是与; !它不应该在那里...这只是看起来奇怪的,而不是在语言的精神。您可以选择拥有code,它扩展到两个; 成一排,或code,看起来的 UN-C-ISH 的:)

The problem is with the ; ! It shouldn't be there... and that would just look strange and not in the spirit of the language. You can either choose to have a code that expands in to two ; in a row, or a code that looks un-c-ish :)

在另一方面,在做的,而施工不存在这样的问题。

On the other hand, the do-while construction does not have that problem.

此外,如其他人所说,有一个其他问题:

Also, as others mentioned, there's an else problem:

if (1)
    my_code;
else { ... }

忽略; issuse,在其他块现在属于错的,如果

Ignoring the ; issuse, the else block now belongs to the wrong if.

这篇关于做{}而(0)与如(1){}中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆