Iulian Onofrei Iulian Onofrei - 4 months ago 7
Objective-C Question

Is #if preprocessor macro "running" #ifdef behind the scenes in Objective-C?

If I create a preprocessor macro named

DEBUG
for the
Debug
configuration of a project's target with the value
1
, and not for the
Release
configuration, I find that using

#if DEBUG
...
#endif


compiles for
Release
builds too.

Firstly, is it checking if
DEBUG
is defined and after that if it evaluates to
true
? If yes, is it ok (or recommended) to use it this way instead of

#ifdef DEBUG
#if DEBUG
...
#endif
#endif


?

Answer

It's not recommended to use #if VARIABLE without checking that VARIABLE has been defined.

When #if evaluates the expression, it does the following:

  1. It expands all macros in the expression (which means that an symbol which has not been #defined will be unchanged.)

  2. It parses the result as an integer arithmetic expression, replacing any identifier with the integer 0.

So if DEBUG has not been #defined as a macro,

#if DEBUG

will be the same as

#if 0

which will also have the same effect as #ifdef DEBUG.

If you define DEBUG on the command-line with -DDEBUG, then there is an implicit

#define DEBUG 1

before the file is preprocessed, with the result that

#if DEBUG

is the same as

#if 1

which is also the same as #ifdef DEBUG.

However. If you did the following:

#define DEBUG
#if DEBUG
//  ... stuff
#endif

the the #if will expand to:

#if

and you'll get an error message:

file.m:2:6: error: #if with no expression

As a result, it is unwise to use #if VARIABLE, unless you know for sure that VARIABLE has been defined as an integer.

Comments