易截截图软件、单文件、免安装、纯绿色、仅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++学习应该注意的几个细节


给我们上ASP.NET的老师在讲解C#的时候,总是要询问我们C#和C/C++间的不同之处,或者一些细节问题,但是平时不怎么注意,还真把我们给问到了!!
一.不经过中间变量怎样交换两个数据 int a=25;b=10;
解法: a=a+b;//35
        b=a-b;//25
      ......

C/C++也可以写的很安全!

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

Androd的C/S之一——View和SurfaceFlinger

    客户端部分:
    这样看来Android的View的创建和X的窗口创建是很类似的:客户端发送请求,让服务器端来实现具体的操作。
    服务器部分还没有看明白,下回再整。 ......

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


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

对C/C++可变参数表的深层探索


引言
  C/C++语言有一个不同于其它语言的特性,即其支持可变参数,典型的函数如printf、scanf等可以接受数量不定的参数。如:
printf ( "I love you" ); 
printf ( "%d", a );
printf ( "%d,%d", a, b );
  第一、二、三个printf分别接受1、2、3个参数,让我们看看printf函数的原型:
int printf ( const ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号