45

I understand how to use a preprocessor directive like this:

#if SOME_VARIABLE
    // Do something
#else
    // Do something else
#endif

But what if I only want to do something IF NOT SOME_VARIABLE.

Obviously I still could do this:

#if SOME_VARIABLE

#else
    // Do something else
#endif

. . . leaving the if empty, But is there a way to do:

#if not SOME_VARIABLE
   // Do something
#endif

Apple documentation here suggests not, but this seems like a very basic need.

Basically I want to do the preprocessor equivalent of:

if(!SOME_VARIABLE)(
{
   // Do Something
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Undistraction
  • 42,754
  • 56
  • 195
  • 331

3 Answers3

92

you could try:

#if !(SOME_VARIABLE)
   // Do something
#endif
CarlJ
  • 9,461
  • 3
  • 33
  • 47
24

Are you trying to check if something is defined or not? If yes, you can try:

#ifndef SOME_VARIABLE

or

#if !defined(SOME_VARIABLE)

xuzhe
  • 5,100
  • 22
  • 28
  • My question has nothing to do whether it is defined or not. Just wanted a way to do the equivalent if if(!some_var){//do something}; – Undistraction Jun 04 '12 at 11:58
4

The Apple documentation (If - The C Preprocessor) is correct and this is the way that C pre-processor statements have been since the dawn of time. As per that same documentation all you can do is craft an expression that evaluates to either zero or a non-zero value and use that.

Meccan's answers is correct as TARGET_IPHONE_SIMULATOR is defined as TRUE or FALSE depending on the platform, so the expression will evaluate to either zero or a non-zero amount.

In general these macros (#if etc) are used for including or excluding things based on whether a symbol is defined or not. For that use case the pre-processor has #ifdef and #ifndef which covers what has historically been accepted as the most important cases.

Also given that the subject of these statements can only be other pre-processor defined symbols (via #define) then this limitation is reasonable.

Peter M
  • 7,309
  • 3
  • 50
  • 91