Iulian Onofrei Iulian Onofrei - 1 year ago 66
Objective-C Question

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

If I create a preprocessor macro named

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


compiles for
builds too.

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

#ifdef DEBUG


Answer Source

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,


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


is the same as

#if 1

which is also the same as #ifdef DEBUG.

However. If you did the following:

#define DEBUG
//  ... stuff

the the #if will expand to:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download