Simple C macro for debugging

February 28, 2010

[Warning: This post is a backup recovery from my previous Wordpress blog. All content was automatically converted accessing a MySQL database using a Python script (details). Mostly are in Portuguese but if you are interest I can translate to English. If you found any problem dont’t hesitate to contact me in comments.]

A little trick if you use printf to debug information in your code and don’t like to comment/uncomment.

#include 

#define dprintf if (debug) printf

const char debug = 1; /* or 0 if you want disable debug */ 

int main(int argc, char *argv[] ) {
     dprintf ("debug message");
     return 0;
}
</pre>

Remember that using printf is just one way to debug your code and an excess can impair the efficiency to analyze the situation or catch bugs. If you need start your program, specifying anything that might affect its behavior; make your program stop on specified conditions; examine what has happened, when your program has stopped or change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another; use programs such as GDB or Valgrind (especially to memory management issues)