为什么在宏定义中在(0)时使用{}?

编程入门 行业动态 更新时间:2024-10-22 08:07:15
本文介绍了为什么在宏定义中在(0)时使用{}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复:

我遇到了如下代码:

I met code like below:

#define ev_io_init(ev,cb,fd,events) \ do { \ ev_init ((ev), (cb)); \ ev_io_set ((ev),(fd),(events)); \ } while (0)

我想知道为什么作者使用在此(0)时执行{}。 与此有什么区别吗?

I want to know why the author use do { } while (0) here. Is there any difference with this?

#define ev_io_init(ev,cb,fd,events) { \ ev_init ((ev), (cb)); \ ev_io_set ((ev),(fd),(events)); \ }

BTW:代码来自libev,ev_local.h

BTW: the code is from libev, ev_local.h

推荐答案

考虑 if(something)function1(); else function2();

如果 function1()实际上是一个宏,使用 {} 要求您在使用时省略分号,但是做{} while(0)您使用与实函数完全相同的语法。

If function1() is actually a macro, just using { } requires you to omit the semicolon at the point of use, but do { } while(0) lets you use exactly the same syntax as for a real function.

(根本不使用任何块构造只会生成完全损坏的代码,natch)

(Not using any kind of block construct at all would just generate completely broken code, natch)

更多推荐

为什么在宏定义中在(0)时使用{}?

本文发布于:2023-11-29 16:45:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!