tags:

views:

54

answers:

1

I was browsing some code and I came across this macro definition

#define D(x) do { } while (0)

And its used in the code like this,

D(("couldn't identify user %s", user));

I ran the code, and that particular line doesn't do anything. So, why would some one define a macro like that?

In case you're wondering, that macro is defined in the _pam_macros.h header file.

+8  A: 

Most likely D is for debugging, and there's an #ifdef elsewhere that makes it do something more useful if debugging is enabled, like output the message or log it to a file. The do/while loop is to make it require a semi-colon at the end, so the user can call it as D(...); instead of just D(...) (see this post)

Michael Mrozek
The `do ... while(0)` thing makes the `;` be parsed gently and the macro behave (a least a very little bit) like a statement. (was already explained in the liked post)
jdehaan
Since the body is empty, wouldn't this have been just as good? `#define D(x)` Then `D(x);` becomes `;` which is a nice single statement.
R..
@R Good point, I think replacing with an empty body is safe and more common; probably the writer has just had enough bugs from macro expansions that they're in the habit of wrapping every macro in `do/while(0)` even if it's unnecessary
Michael Mrozek