C:{...} while(0)吗? [英] C: do {...} while(0)?

查看:63
本文介绍了C:{...} while(0)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
为什么有时会出现C/C ++宏中的do/while和if/else语句毫无意义吗?
do {…}而(0)有什么用?

我正在处理一些填充有这样的宏的C代码:

I'm working on some C code filled with macros like this:

#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)

任何人都可以解释此宏的作用,以及为什么需要 {{while(0) )吗?那不是只执行一次代码吗?

Can anyone explain what this macro does, and why do {} while(0) is needed? Wouldn't that just execute the code once?

推荐答案

do { stuff() } while(0);

做的事情与stuff()完全相同.那有什么大不了的呢?问题在于宏的语法.假设我们定义了这样的宏:

is doing the exact same thing as stuff(). So what's the big deal, then? The issue is with the syntax of macros. Suppose we defined the macro like:

#define SAFE_FREE(x) if ((x) != NULL) { free(x); x=NULL; }

然后,有两个问题.第一个相对较小:使用SAFE_FREE不再需要结尾的分号.不过,更重要的是,代码如下:

Then, there are two issue. The first is relatively minor: uses of SAFE_FREE no longer require a trailing semi-colon. More importantly, though, code like:

if (...)
  SAFE_FREE(x)
else
   stuff();

将扩展为:

if (...)
  if ((x) != NULL) {
    free(x);
    x = NULL;
  } else
    stuff();

如上所述定义宏可以防止上述奇怪的行为,因为 do {...} while(0)的行为就像没有分号的语句一样.

Defining the macro as above prevents weird behavior as above, since do { ... } while(0) acts just like a statement without its semicolon.

这篇关于C:{...} while(0)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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