易截截图软件、单文件、免安装、纯绿色、仅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.


相关文档:

C/C++ 文件读写操作总结(2)

五、文件定位
  和C的文件操作方式不同的是,C++ I/O系统管理两个与一个文件相联系的指针。一个是读指针,它说明输入操作在文件中的位置;另一个是写指针,它下次写操作的位置。每次执行输入或输出时,相应的指针自动变化。所以,C++的文件定位分为读位置和写位置的定位,对应的成员函数是 seekg()和 seekp(),seekg()是 ......

谈C/C++指针精髓(一,二,三)

[
摘要] 
 
指针是
C和
C++语言编程中最重要的概念之一,也是最容易产生困惑并导致程序出错的问题之一。利用指针编程可以表示各种数据结构
, 通过指针可使用主调函数和被调函数之间共享变量或数据结构,便于实现双向数据通讯;并能像汇编语言一样处理内存地址,从而编出精练而高效的程序。指针极大地丰富了 ......

c/c++语言问题中可变参数


 va_list是c/c++语言问题中解决可变参数的一组宏.先来看一个程序例子吧.
view plaincopy to clipboardprint?
#include <stdarg.h>   
/** 函数名:max  
  * 功能:返回n个整数中的最大值  
  *  参数:num:整数的个数 . ......

ANSI C读书笔记系列之字符集篇 第四章 字节序

"endian"这个词出自<<格列佛游记>>,小人国的内战就源于吃鸡蛋时是究竟从大头(Big-Endian)敲开还是从小头(Little-Endian)敲开.我们一般将endian翻译成"字节序",将big endian和little endian称作"大端"和"小端".
在计算机科学领域中,字节序是指存放多字节数据的字节的顺序,典型的情况是整数在内存中的存放方式和 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号