易截截图软件、单文件、免安装、纯绿色、仅160KB

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.


相关文档:

Perl文件测试符 C的用法

在Perl的各种文件测试运算符中,最有用的运算符之一就是 -C 了。
它返回的是文件的ctime到程序启动的那一时刻经过的天数。
如果不是整数天,返回值就带有小数。
这个运算符经常用来检测文件是否过期,比如判断文件距离上次修改是否超过了3天,
如果超过就将其删除。但是,你是否真正理解 -C 的工作原理呢?
何谓ctime ......

关于《0 bug C/C++商用工程之道》的一处bug

这两天有很多朋友已经买了书了,并且开始看,呵呵,我心里也很高兴。
嗯,要说江湖上藏龙卧虎呢,这不,这才几天时间,已经有朋友指出我书中的一处明显错误,这里我正式给大家说明一下,免得对各位读者有个不好的误导。
问题出在第26页的一个图以及其相关文字。这是第二章基础知识的第一节,其实就是关于内存的讲解,大家 ......

keil c union 存储的问题

     3: int main()
     4: {
     5:    int i = 1,j;
     6:    union test{
     7:       int m;
     8:  ......

scanf("%c")

今天做了ACM1010
代码都对就是怎么也不能AC。那个郁闷啊!一晚上都想那个了。
本来有俩组输入,可是输出的结果就一组。仔细看输入,竟然自动换行了,奇怪,这是咋回事。
猜测可能是读入了换行符。同样的问题这C++中就没有啊!
最后通过加getchar();AC通过。 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号