11

For debug logging, I have often seen and used something like

#ifdef DEBUG
    #define DLOG(fmt, args...) printf("%s:%d "fmt,__FILE__,__LINE__,args)
#else
    #define DLOG(fmt, args...)
#endif

but in a number of places, I have seen the second #define replaced with

#define DLOG(fmt, args...) do {} while (0)

In particular, there's this answer, and the comment on this other answer to the same question suggests that the problem would be in a situation like

if (condition)
    DLOG("foo");

though my quick test suggests that the resulting semicolon on the line by itself will serve as the no-op statement inside the conditional.

Is one or the other of nothing and do {} while (0) better? If so, why? Is there something else that's even better?

Community
  • 1
  • 1
Isaac
  • 10,668
  • 5
  • 59
  • 68
  • possible duplicate of [do { ... } while (0) what is it good for?](http://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for) – Carl Norum Jul 18 '12 at 19:54

3 Answers3

10

A semicolon by itself has two drawbacks:

  • Users of your macro can write it without a semicolon, and the compiler will not complain, and
  • Some compilers may issue a warning about a possibly stray semicolon.

The do {} while (0) trick addresses both these concerns:

DLOG("foo") // No semicolon

will trigger an error, and the compiler will not warn you about a "stray" semicolon.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
6

See C #define macro for debug printing for an explanation of why you want a different form of no-op. You want to have the compiler parse the debug printing code even when you aren't using it so that errors do not creep in.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

The quick answer is that the do/while method lets you have a multi-statement replacement and still use it as a single statement in an if case like you have in your question. For a single expression replacement, I don't think there's any difference.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469