C++ Macros – Is Using Macros for Conditional Compilation Good Practice?

cmacros

Let's say I want to have several types of output messages in my code. One of them is DEBUG, which is printed only, when the code is compiled in Debug mode.

Usually I'd have to write something like

#ifdef DEBUG
    std::cout << "Debug message" << std::endl;
#endif

which is pretty cumbersome and annoying to use in many places.

Is it a good practice to define a macro for the code snippet, so you'd use it this way?

MSG_DEBUG("Debug message")

Or is there any other, more elegant way how to deal with it without macros? I'm interested about possible solutions both in C and C++, as I'm using both languages in different projects.

Best Answer

Sure, if you're OK with using macros in the first place, then defining a parametrized one rather than keep repeating the same conditional code is certainly preferable by any measure of good coding.

Should you use macros at all? In my view you should, since it's accepted practice in C, and any macro-less solution would require at least something being executed even outside of debug mode. The typical C programmer will pick a slightly ugly macro over unnecessary run-time effort any time.