Why use loop instead block in macros in C [duplicate]
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.
精彩评论