views:

255

answers:

2

What is the difference (if any) between the two following preprocessor control statements.

#if

and

#ifdef
+12  A: 
#ifdef FOO

is a shortcut for:

#if defined(FOO)

#if can also be used for other tests or for more complex preprocessor conditions.

#if defined(FOO) || defined(BAR)
ereOn
or my favorite #if 0 instead of commenting multiple lines.
Anders K.
`if (0)` allows the lines to be compiled in Debug mode, so that you can jump in the block when debugging...
pascal
@pascal: that sounds highly compiler/env specific. C++ doesn't even define a debug mode (though NDEBUG has meaning in the context of assert). ;-P
Tony
@Tony, pascal: I think Pascal is not talking about #if (0) but if (0). The code won't be executed but compiled i.e. instructions are generated. If optimizations are enabled (typically in "release mode") no CPU instructions are generated.
ur
If I could have accepted your answer too I would have. +1 instead. :-)
Konrad
@Konrad: No problem ;) Glad I could help.
ereOn
Can we also write #if null?
fahad
+24  A: 

You can demonstrate the difference by doing:

#define FOO 0
#if FOO
  // won't compile this
#endif
#ifdef FOO
  // will compile this
#endif

#if checks for the value of the symbol, while #ifdef checks the existence of the symbol (regardless of its value).

Greg Hewgill
+1 for explicitly pointing out that defining something to zero will disable #if, but not #ifdef.
DevSolar
If FOO defined non-zero than the compiler compiles.Why?
fahad
@fahad: `#if` checks the *value* of the symbol to see whether it is non-zero (true) or zero (false). Then the block is compiled if the result is true.
Greg Hewgill
@Greg : thanks..
fahad