13

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.

Eenoku
  • 327

3 Answers3

19

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.

Kilian Foth
  • 110,899
14

There's an element of personal preference here, but in C++ I prefer to do this in the header file:

#ifdef _DEBUG
    void DebugMessage(...);
#else
    inline void DebugMessage(...) {}
#endif

So that the function is inlined away in release builds, but is a proper function in the debug build so you can have proper type checking, sensible error messages, etc. and the ability to add further functionality (logging maybe?) later.

Obviously, you also need to encase the corresponding definition of the function in the .cpp file in an #ifdef _DEBUG block.

Martin Ba
  • 7,862
2

Definitely, just make sure you're not stepping on the code guidelines given by your team. Make sure no other code in the system tries to reach the same functionality via a general if condition.

James O
  • 21