DEBUG macros in C++

user277465 picture user277465 · Jan 10, 2013 · Viewed 88.8k times · Source

I just encountered a DEBUG macro in C that I really like

#ifdef DEBUG_BUILD
#  define DEBUG(x) fprintf(stderr, x)
#else
#  define DEBUG(x) do {} while (0)
#endif

I'm guessing a C++ analogue would be :-

#ifdef DEBUG_BUILD
#  define DEBUG(x) cerr << x
#else
#  define DEBUG(x) do {} while (0)
#endif
  1. Is the second code snippet analogous to the one in C?
  2. Do you have any favorite C++ debug macros?

EDIT : By "Debug Macros" I mean "macros that might come in handy while running a program in debug mode".

Answer

MvG picture MvG · Jan 10, 2013

Is the second code snippet analogous to the one in C?

More or less. It's is more powerful, as you can include <<-separated values in the argument, so with a single argument you get something that would require a variable number of macro arguments in C. On the other hand, there is a slim chance that people will abuse it by including a semicolon in the argument. Or even encounter mistakes due to a forgotten semicolon after the call. So I'd include this in a do block:

#define DEBUG(x) do { std::cerr << x; } while (0)

Do you have any favourite C++ debug macros?

I like the one above and use it quite often. My no-op usually just reads

#define DEBUG(x)

which has the same effect for optimizing compilers. Although the comment by @Tony D below is correct: this can leave some syntax errors undetected.

I sometimes include a run-time check as well, thus providing some form of a debug flag. As @Tony D reminded me, having an endl in there is often useful as well.

#define DEBUG(x) do { \
  if (debugging_enabled) { std::cerr << x << std::endl; } \
} while (0)

Sometimes I also want to print the expression:

#define DEBUG2(x) do { std::cerr << #x << ": " << x << std::endl; } while (0)

In some macros, I like to include __FILE__, __LINE__ or __func__, but these are more often assertions and not simple debug macros.