C MacrosΒΆ
While learning C, I learned that macros could be dangerous so I was always wary of using them unless I had to (for example when using the GTK library). Last week, a friend of mine asked me if I could design a macro that would insert // if something were defined and would not insert anything if the variable were not defined. The solution was easy.
#ifdef DEBUG
#define DBGONLY //
#else
#define DBGONLY
#endif
Clearly, he wanted to manage when he would print out debugging information, so his code (when read by mere humans) would look like
int func(void){
/* Variable declarations */
DBGONLY printf("Debugging information.\n");
/* Rest of function */
}
When interpretted by the preprocessor, that function can evaluate to two different things depending on how he compiles the program. If he uses the -D flag with option DEBUG it will look like:
int func(void){
/* Variable declarations */
printf("Debugging information.\n");
/* Rest of function */
}
Thus enabling “Debugging information” to be printed and giving the developer more information to fix problems. Otherwise, it will look like
int func(void){
/* Variable declarations */
// printf("Debugging information.\n");
/* Rest of function */
}
However, I like to ensure that my code will compile in as many places as possible so I compile against older C standards, particularly ones where // isn’t valid language for commenting. This made me come up with a second macro.
#ifndef DEBUG
#define DBGONLY(a) /* a */
#else
#define DBGONLY(a) a
#endif
If you’re unfamiliar with how this would work, if I define the macro ‘DEBUG‘, it will just replace what it wraps with itself. If the macro is not defined, it will validly comment it out. So that same function would look like this:
int func(void){
/* Variable declarations */
DBGONLY(printf("Debugging information.\n");)
/* Rest of function */
}
Without the commandline option -DDEBUG, the function looks like:
int func(void){
/* Variable declarations */
/* printf("Debugging information.\n"); */
/* Rest of function */
}
With it, the function will print the debugging information. This seemed to amaze my friend and I thought it was a clever way of avoiding my usual syntax of:
int func(void){
/* Variable declarations */
#ifdef DEBUG
printf("Debugging information.\n");
#endif
/* Rest of function */
}
Which is needlessly verbose and artificially inflates the line count of a file. Naturally anything that makes the code easier to read and write is something I like to employ.