C multi line macro: do/while(0) vs scope block
http://docs.google.com/View?docid=ajbgz6fp3pjh_2dwwwwt#_38239340844832237
It is not about optimization.
The whole idea of using 'do/while' version
is to make a macro which will
expand into a regular statement, not into a
compound statement. This is
done in order to make the use of function-style
macros uniform with the
use of ordinary functions in all
contexts.
Consider the following code sketch
if
(<condition>)
foo(a);
else
bar(a);
where 'foo' and 'bar'
are ordinary functions. Now imagine that you'd
like to replace function 'foo'
with a macro of the above nature
if
(<condition>)
CALL_FUNCS(a);
else
bar(a);
Now, if your
macro is defined in accordance with the second approach
(just '{' and '}')
the code will no longer compile, because the 'true'
branch of 'i' is now
represented by a compound statement. And when you
put a ';' after this
compound statement, you finished the whole 'if'
statement, thus orphaning the
'else' branch (hence the compilation error).
One way to correct this
problem is to remember not to put ';' after
macro "invocations"
if
(<condition>)
CALL_FUNCS(a)
else
bar(a);
This will compile
and work as expected, but this is not uniform. The
more elegant solution is
to make sure that macro expand into a regular
statement, not into a compound
one. One way to achieve that is to define
the macro as follows
#define
CALL_FUNCS(x) \
do { \
func1(x); \
func2(x); \
func3(x); \
}
while (0)
Now this code
if
(<condition>)
CALL_FUNCS(a);
else
bar(a);
will compile
without any problems.
However, note the small but important difference
between my definition
of 'CALL_FUNCS' and the first version in your message.
I didn't put a
';' after '} while (0)'. Putting a ';' at the end of that
definition
would immediately defeat the entire point of using 'do/while' and
make
that macro pretty much equivalent to the compound-statement version.
相关文档:
from: 《自己动手写操作系统》
1. 中断向量表 查看 linux/init/main.c in http://lxr.linux.no/#linux+v2.6.32/init/main.c
2.
; [root@XXX XXX]# nasm -f elf foo.asm -o foo.o
; [root@XXX XXX]# gcc -c bar.c -o bar.o
; [root@XXX XXX]# ld -s foo.o bar.o -o foobar
; [root@XXX XXX]# ./foobar
; the 2nd on ......
今天在CC上看到evangel在招人,上面写了一条数据解析,我想应该就是对XML的解析吧,暂且这样理解了,呵呵。下午搜索了一点东西自己弄了一个XML然后读读看看,现在仅仅是读出了一些东西,先保存代码,待后续更新!
这个是我创建的xml文件,用于测试用的:
<?xml version="1.0" e ......
这两天有很多朋友已经买了书了,并且开始看,呵呵,我心里也很高兴。
嗯,要说江湖上藏龙卧虎呢,这不,这才几天时间,已经有朋友指出我书中的一处明显错误,这里我正式给大家说明一下,免得对各位读者有个不好的误导。
问题出在第26页的一个图以及其相关文字。这是第二章基础知识的第一节,其实就是关于内存的讲解,大家 ......
va_list是c/c++语言问题中解决可变参数的一组宏.先来看一个程序例子吧.
view plaincopy to clipboardprint?
#include <stdarg.h>
/** 函数名:max
* 功能:返回n个整数中的最大值
* 参数:num:整数的个数 . ......
http://os.51cto.com 2008-03-21 11:15 佚名 赛迪网
摘要:学会使用vim/emacs,vim/emacs是linux下最常用的源码编辑器,不光要学会用它们编辑源码,还要学会用它们进行查找、定位、替换等。新手的话推荐使用vim,这也是我目前使用的文本编辑器。
标签:Linux C语言 编程
Or ......