M.S Chaudhari M.S Chaudhari - 3 months ago 8
C Question

Is #if defined MACRO equivalent to #ifdef MACRO?

I have code that I want to have two modes, debug and verbose. I define them in my header file as,

#define verbose TRUE
#define debug TRUE


In my code so far, I have just been using

#if(debug)
//code
#endif


but is it more proper to use

#ifdef debug
// code
#endif


I read something about preprocessor macros but it didn't make sense at the time. So, I have question, Is
#if defined MACRO
equivalent to
#ifdef MACRO
? and which is better to enabling/disabling particular section of code?

Answer
#ifdef MACRO
#if defined (MACRO)

will do the exact same thing. However, the defined (MACRO) is just an expression that evaluates to 0 or 1 inside the #if, and it can be combined with other expressions. For example

#if defined (MACRO) && ! defined (MACRO2)
    // Do this
#else
    // Do that
#endif

Try doing that with #ifdef - you can't unless your code gets really clumsy.