The correct C no-op preprocessor macroprocessor

For debug logging, I often saw 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 noticed that the second is #definereplaced by

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

In particular, there this answer and the comment of this other answer to the same question suggests that the problem will be in a situation such as

if (condition)
    DLOG("foo");

although my quick test assumes that the resulting semicolon in the string itself will serve as the no-op operator inside the conditional expression.

Is this or that of nothing do {} while (0)better? If so, why? Is there anything else that is even better?

+5
source share
3 answers

#define , , no-op. , , , .

+5

:

  • , ,
  • .

do {} while (0) :

DLOG("foo") // No semicolon

, "" .

+7

The quick answer is that the do / while method allows you to replace multiple statements and use it as one statement in the case ifas in your question. To replace one expression, I don’t think there is any difference.

0
source

All Articles