本文介绍了为什么在宏定义中在(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)时使用{}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!