Ohh !!! and I thought do…while(0) is just useless

Over the period of years, I saw following kind of code in many places

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

But this is not useless but a clear trick to avoid unwanted Empty Expression

Consider you have defined the same macro as follows

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

and you are using the same as follows in your main code

if (corge)

Above code would be expanded as follows

if (corge)
  f(corge); g(corge);

This would cause compiler to cry from bottom of its neck. This is not what you wanted, and this is where do…while(0) trick comes as a savior.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s