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.
相关文档:
Boss说,要看OpenGL,看了快一个月,总算出了个像样的东西,用C写了个3D迷宫,
虽然只有350行
代码,不过边学边写,足足写了一周时间,还是小有成就感的,活活活!
&n ......
今天在CC上看到evangel在招人,上面写了一条数据解析,我想应该就是对XML的解析吧,暂且这样理解了,呵呵。下午搜索了一点东西自己弄了一个XML然后读读看看,现在仅仅是读出了一些东西,先保存代码,待后续更新!
这个是我创建的xml文件,用于测试用的:
<?xml version="1.0" e ......
在编程的过程中,文件的操作是一个经常用到的问题,在C++Builder中,可以使用多种方法对文件操作,下面我就按以下几个部分对此作详细介绍,就是:
1、基于C的文件操作;
2、基于C++的文件操作;
3、基于WINAPI的文件操作;
4、基于BCB库的文件操作;
5、特殊文件的操作。
壹、基于C的文件操作
在ANSI C中 ......
[
摘要]
指针是
C和
C++语言编程中最重要的概念之一,也是最容易产生困惑并导致程序出错的问题之一。利用指针编程可以表示各种数据结构
, 通过指针可使用主调函数和被调函数之间共享变量或数据结构,便于实现双向数据通讯;并能像汇编语言一样处理内存地址,从而编出精练而高效的程序。指针极大地丰富了 ......
在Linux C编程中使用Unicode和UTF-8
目前各种Linux发行版都支持UTF-8编码,当前系统的语言和字符编码设置保存在一些环境变量中,可以通过locale命令查看:
$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US ......