Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#ifdef DEBUG versus #if DEBUG

It is unclear to me when using compiler directives which of the below two code snippets is correct/preferred and why. It seems that most developers and Open Source projects I've seen use the first but I have seen the second used frequently as well.

#ifdef DEBUG
[self doSomethingOnlyWhenDebugging];
#endif

VERSUS

#if DEBUG
[self doSomethingOnlyWhenDebugging];
#endif

Which of the above code snippets is preferable for running code only while debugging and why? My guess is that the first will run if DEBUG is defined as TRUE or FALSE where the second will run only if DEBUG is defined and set to TRUE. Is that correct?

like image 399
lidsinker Avatar asked Apr 26 '13 21:04

lidsinker


2 Answers

You are correct. #if DEBUG will not evaluate if DEBUG is defined as 0.

As for when to use each, you can stick to using #ifdef for anything where you only need to add code if the preprocessor definition is present, such as adding debug logging. If you need to inspect the value and go down different compilation paths, then I would use a 0 or 1. A good example of that is TARGET_IPHONE_SIMULATOR, which is always defined for an iOS project, but only 1 if you’re compiling for the simulator.

like image 61
Jeff Kelley Avatar answered Nov 06 '22 15:11

Jeff Kelley


As I know, the finest choice is:

#ifndef DEBUG
    NSLog(@"-1");
#elif DEBUG == 0
    NSLog(@"0");
#else
    NSLog(@"%d", DEBUG);
#endif

then, you will know #ifndef DEBUG is preferred above all others.

There is a simpler choice:

#if DEBUG == 0 // DEBUG is not defined or defined to be 0
    // do sth
#else
    // do sth
#endif

However, if -Wundef compiler flag is on, there might be a warning with #if DEBUG == 0.

like image 8
DawnSong Avatar answered Nov 06 '22 16:11

DawnSong