c++ - Why use apparently meaningless do-while and if-else statements in macros? -


in many c/c++ macros i'm seeing code of macro wrapped in seems meaningless do while loop. here examples.

#define foo(x) { f(x); g(x); } while (0) #define foo(x) if (1) { f(x); g(x); } else 

i can't see do while doing. why not write without it?

#define foo(x) f(x); g(x) 

the do ... while , if ... else there make semicolon after macro means same thing. let's had second macro.

#define bar(x) f(x); g(x) 

now if use bar(x); in if ... else statement, bodies of if statement not wrapped in curly brackets, you'd bad surprise.

if (corge)   bar(corge); else   gralt(); 

the above code expand into

if (corge)   f(corge); g(corge); else   gralt(); 

which syntactically incorrect, else no longer associated if. doesn't wrap things in curly braces within macro, because semicolon after braces syntactically incorrect.

if (corge)   {f(corge); g(corge);}; else   gralt(); 

there 2 ways of fixing problem. first use comma sequence statements within macro without robbing of ability act expression.

#define bar(x) f(x), g(x) 

the above version of bar bar expands above code follows, syntactically correct.

if (corge)   f(corge), g(corge); else   gralt(); 

this doesn't work if instead of f(x) have more complicated body of code needs go in own block, example declare local variables. in general case solution use do ... while cause macro single statement takes semicolon without confusion.

#define bar(x) { \   int = f(x); \   if (i > 4) g(i); \ } while (0) 

you don't have use do ... while, cook if ... else well, although when if ... else expands inside of if ... else leads "dangling else", make existing dangling else problem harder find, in following code.

if (corge)   if (1) { f(corge); g(corge); } else; else   gralt(); 

the point use semicolon in contexts dangling semicolon erroneous. of course, (and should) argued @ point better declare bar actual function, not macro.

in summary, do ... while there work around shortcomings of c preprocessor. when c style guides tell lay off c preprocessor, kind of thing they're worried about.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -