开发者

Why use loop instead block in macros in C [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?

Hello, in many C macros programmers use special one-loop, for example:

#define do_something(a) do { ex开发者_如何学Pythonecute(a); count(a); } while(0)

because of when you want to do this macro in loop and you don't use "{}". Why they aren't using simple block instead? I mean, doesn't

#define do_something(a) { execute(a); count(a); }

have the very same effect?


Because

if( something ) do_something(a);
else something_else();

expands to:

if( something ) do { execute(a); count(a); } while(0);
else something_else();

which is correct, but:

if( something ) { execute(a); cout(a); };
else something_else();

would not be correct (the superfluous ";").


if (cond)
   do_something(exp);
else 
   do_something_else(exp);

would not be valid C.


Another reason for this: You can use break to get out of the while loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜