The difference between #if and #ifdef in C

I often see people use #if and #ifdef interchangeably.

#if MYMACRO
...
#else
...
#endif

 

#ifdef MYMACRO
...
#else
...
#endif

They seem to achieve the same result. If MYMACRO was defined, the first piece of code is compiled. If MYMACRO was not defined, the second piece of code is compiled. However,the correct usage is the second one. According to the official document of the syntax of #if, the stuff after #if must be an integer constant expression. If the integer constant expression evaluates to 0, the second piece of code is compiled;otherwise, the first piece of code is compiled. However, #if can be followed by any identifier not just an integer constant expression. If the identifier is not defined, it evaluates to 0.

On the other hand, #ifdef can only be followed by an identifier. If the identifier is defined, i.e., the identifier is actually a macro, the code below it is compiled. If not, the code below it is not compiled.

Since both #if and #ifdef can be followed by an identifier, what is their difference? Well, #ifdef and #if have no difference for most of the values the macro was defined. But if you define the macro MYMACRO as 0, #if and #ifdef have the opposite effect. The code below #if is not output by the pre-processor while the the code right below #ifdef is output because #ifdef just cares about if the macro was defined, does not care about the value of the macro. Another difference between #if and #ifdef is that if the macro was defined as empty, i.e.,

#define MYMACRO

#if  MYMACRO
...
#else
...
#endif

Now the compiler complains an error because it expects an integer expression or an identifier after #if while there is nothing after #if after the macro substitution. #ifdef does not have this problem, as I said, #ifdef only cares about whether the identifier after it was defined or not, not its value, even its value is empty.

One last word, #ifdef is the same as #if defined, #ifndef is the same as #if !defined.

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply