Do-While and if-else statements in C/C++ macros

原贴: http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros

In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.

#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else

I can't see what the do while is doing. Why not just write this without it?

#define FOO(X) f(X); g(X)
=================================================================================================================

下面是回答很帅:

------------------------------------------------------------------------------------------------------------------------------------------------

The do ... while and if ... else are there to make it so that a semicolon after your macro always means the same thing. Let's say you had something like your second macro.

#define BAR(X) f(x); g(x)

Now if you were to use BAR(X); in an if ... else statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.

if (corge)
  BAR(corge);
else
  gralt();

The above code would expand into

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

which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because the following is also syntactically incorrect.

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

There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.

#define BAR(X) f(X), g(X)

The above version of bar BAR expands the above code into what follows, which is syntactically correct.

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

This doesn't work if instead of f(X) you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something likedo ... while to cause the macro to be a single statement that takes a semicolon without confusion.

#define BAR(X) do { \
  int i = f(X); \
  if (i > 4) g(i); \
} while (0)

You don't have to use do ... while, you could cook up something with if ... else as well, although when if ... else expands inside of an if ... else it leads to a "dangling else", which could make an existing dangling else problem even harder to find, as in the following code.

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

The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare BAR as an actual function, not a macro.

In summary, the do ... while is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.

------------------------------------------------------------------------------------------------------------------------------------------------

Macros are copy/pasted pieces of text the pre-processor will put in the genuine code; the macro's author hoping the replacement will produce valid code.

So there are three good "tips" to succeed in that

Help the macro behaves like genuine code

Normal code is usually ended by a semi-colon. Should the user view code not needing one...

doSomething(1) ;
DO_SOMETHING_ELSE(2)  // <== Hey? What's this?
doSomethingElseAgain(3) ;

It means the user expects the compiler to produce an error if the semi-colon is absent.

But the real real good reason is that at some time, the macro's author will perhaps need to replace the macro with a genuine function (perhaps inlined). So the macro should really behave like one.

So we should have a macro needing semi-colon.

Produce a valid code

As shown in jfm3's answer, sometimes, the macro contains more than one instruction. And if the macro is used inside a if statement, this will be problematic:

if(bIsOk)
   MY_MACRO(42) ;

This macro could be expanded as:

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

if(bIsOk)
   f(42) ; g(42) ; // was MY_MACRO(42) ;

The g function will be executed no matter the value of the bIsOk bool value.

This means that you must have to add a scope to the macro:

#define MY_MACRO(x) { f(x) ; g(x) ; }

if(bIsOk)
   { f(42) ; g(42) ; } ; // was MY_MACRO(42) ;

Produce a valid code 2

What if the macro is something like:

#define MY_MACRO(x) int i = x + 1 ; f(i) ;

We could have another problem in the following code:

void doSomething()
{
    int i = 25 ;
    MY_MACRO(32) ;
}

Because it would expand as:

void doSomething()
{
    int i = 25 ;
    int i = 32 + 1 ; f(i) ; ; // was MY_MACRO(32) ;
}

This code won't compile, of course. So, again, the solution is using a scope:

#define MY_MACRO(x) { int i = x + 1 ; f(i) ; }

void doSomething()
{
    int i = 25 ;
    { int i = x + 1 ; f(i) ; } ; // was MY_MACRO(32) ;
}

The code behaves correctly again.

Combining semi-colon + scope effects?

There is one C/C++ idiom that produces this effect: The do ... while loop:

do
{
    // code
}
while(false) ;

The do while both can create a scope, thus encapsulating the macro's code and needs a semi-colon in the end, thus expanding into code needing one.

The bonus?

The C++ compiler will optimize away the do/while loop, as the fact its post-condition is false is known at compile time. This means that a macro like:

#define MY_MACRO(x)                                  \
do
{
    const int i = x + 1 ;
    f(i) ; g(i) ;
}
while(false)

void doSomething(bool bIsOk)
{
   int i = 25 ;

   if(bIsOk)
      MY_MACRO(42) ;

   // Etc.
}

while expand correctly as:

void doSomething(bool bIsOk)
{
   int i = 25 ;

   if(bIsOk)
      do
      {
         const int i = 42 + 1 ; // was MY_MACRO(42) ;
         f(i) ; g(i) ;
      }
      while(false) ;

   // Etc.
}

and then compiled and optimized away as:

void doSomething(bool bIsOk)
{
   int i = 25 ;

   if(bIsOk)
   {
      f(43) ; g(43) ;
   }

   // Etc.
}

------------------------------------------------------------------------------------------------------------------------------------------------

@jfm3 - You have a nice answer to the question. You might also want to add that the macro idiom also prevents the possibly more dangerous (because there's no error) unintended behavior with simple 'if' statements:

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

if (test) FOO( baz);

expands to:

if (test) f(baz); g(baz);

which is syntactically correct so there's no compiler error, but has the probably unintended consequence that g() will always be called.

=================================================================================================================


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值