易截截图软件、单文件、免安装、纯绿色、仅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++也可以写的很安全!

今天看到一种比较安全的枚举写法!
enum example
{
item1 = 0,
item2,
item3,
item4,
item5,
max      /* when you want to add element,please add before this */
};
        当你使用它的时候:
example ex1;
        i ......

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


在编程的过程中,文件的操作是一个经常用到的问题,在C++Builder中,可以使用多种方法对文件操作,下面我就按以下几个部分对此作详细介绍,就是:
1、基于C的文件操作;
2、基于C++的文件操作;
3、基于WINAPI的文件操作;
4、基于BCB库的文件操作;
5、特殊文件的操作。
 
壹、基于C的文件操作
  在ANSI C中 ......

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

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

C、C++语言的文件操作

今天归纳总结一下文件操作函数及各个参数的含义:
先介绍一下c++的文件操作,为什么说c++的文件操作呢,因为对于c语言的操作,也有它的函数之不过大同小异罢了。
  在c++的文件操作中有,有一个类对文件操作进行操作,即CFile,下面就写一段代码,来简单的进行介绍。
 CFile cf;
 char zhi[]={1,2};
&n ......

scanf("%c")

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