DEBUG macros in C++

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)