有什么用做的,而(0)当我们定义一个宏? [英] What's the use of do while(0) when we define a macro?

查看:106
本文介绍了有什么用做的,而(0)当我们定义一个宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros\">Do-While在C和if-else语句/ C ++宏

我读了Linux内核,我发现很多宏是这样的:

I'm reading the linux kernel and I found many macros like this:

#define INIT_LIST_HEAD(ptr) do { \
    (ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)

他们为什么用这个,而不是定义它只是在{}?

Why do they use this rather than define it simply in a {}?

推荐答案

您可以用分号遵循它,使它看起来和行为更像一个功能。
它还可以与的if / else子句正确即可。

You can follow it with a semicolon and make it look and act more like a function. It also works with if/else clauses properly then.

如果不同时(0),您的code以上不会与

Without the while(0), your code above would not work with

if (doit) 
   INIT_LIST_HEAD(x);
 else 
   displayError(x);

因为宏分号后会吃else子句,和上面甚至不会编译。

since the semicolon after the macro would "eat" the else clause, and the above wouldn't even compile.

这篇关于有什么用做的,而(0)当我们定义一个宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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