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

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

问题描述

可能的重复:
C/C++ 宏中的 Do-While 和 if-else 语句
do { ... } while (0) — 它有什么用?

我正在阅读 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.

如果没有 while(0),上面的代码将无法使用

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.

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

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