This may be a matter of style, but there’s a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter…
Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:
//---- SomeSourceFile.cpp ---- #define DEBUG_ENABLED (0) ... SomeFunction() { int someVariable = 5; #if(DEBUG_ENABLED) printf('Debugging: someVariable == %d', someVariable); #endif }
Some of the team prefer the following though:
// #define DEBUG_ENABLED ... SomeFunction() { int someVariable = 5; #ifdef DEBUG_ENABLED printf('Debugging: someVariable == %d', someVariable); #endif }
…which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there’s no danger it could destroy other defines elsewhere.
My initial reaction was
#ifdef, of course, but I think#ifactually has some significant advantages for this – here’s why:First, you can use
DEBUG_ENABLEDin preprocessor and compiled tests. Example – Often, I want longer timeouts when debug is enabled, so using#if, I can write this… instead of …
Second, you’re in a better position if you want to migrate from a
#defineto a global constant.#defines are usually frowned on by most C++ programmers.And, Third, you say you’ve a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that
#ifis the preferred choice means that code using#ifdefwill compile -and run- even whenDEBUG_ENABLEDis false. And it’s much easier to track down and remove debug output that is produced when it shouldn’t be than vice-versa.Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your
#define, and because the value is a single lexical token, it’s the one time you don’t need parentheses around it.instead of