做{}而(0) - 宏安全性 [英] do{}while(0) - macro safety
问题描述
我们知道,多行的宏都在做的是围封,而(0)为他们循环安全地在code的任何地方包括在内。
We know that multiline macros have to be inclosed in a do while(0) loop for them to be safely included anywhere in the code.
例如,这是100%安全的:
For example this is 100% safe:
#define swap( a , b ) \
do \
{ \
int t = a ; \
a = b ; \
b = t ; \
} \
while(0)
我想知道这是否是也可以放心与循环外code的一部分的宏,如果它不是,在什么可能发生的情况的问题。
I would like to know if it is also safe to have a macro with a part of the code outside of the loop, and if it isn't, in what circumstances could problems occur.
#define swap( a , b ) \
int t ; \ //should be in the same scope where the macro was called and before the loop
do \
{ \
t = a ; \
a = b ; \
b = t ; \
} \
while(0)
有没有一种安全的方式来实现这一目标,将有什么改变或什么规则应该跟着我,如果它是不是安全。
Is there a safe way to achieve this, what would have to be changed or what rules should I follow if it isn't safe.
推荐答案
这不是在许多方面的安全。首先,如果任何变量称为T已经存在,它不会编译。
It is not safe in many ways. First, if any variable called t already existed, it wouldn't compile.
除此之外,你必须要小心这样的话:
Apart from that, you have to be careful with things like:
if (...)
swap(a,b);
如将它扩展为:
if (...)
int t;
do { ... } while(0);
注意,因为如果没有括号的,如果块主体将只是一个声明。
Note that the if body would be only a declaration because there are no braces for the if block.
你为什么不声明T内的做阻止?
Why don't you declare t inside the do block?
这篇关于做{}而(0) - 宏安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!