ant2009
ant2009

Reputation: 22486

Using #define to define and #if defined to see if it is defined

gcc 4.4.4 c89

I am trying to define something. If it is defined I want to do something, else I want to do something different.

#define PARSE_STRING
    for(i = 0; i < NUMBER_OF_STRINGS; i++) {
#if defined (PARSE_STING)
    /* run code for parsing the strings */
#else
    /* run code that doesn't parse the strings
    }
#endif

When I try the above code in my function, I seem to get other errors else where in my code. However, if I comment out the #define PARSE_STRING it compiles ok. I am just wondering do I need the #define PARSE_STRING?

Many thanks for any suggestions,

====== EDIT with updated solution

Could it be better to do it this way, instead?

#define PARSE_STRING
    for(i = 0; i < NUMBER_OF_STRINGS; i++) {
#if defined (PARSE_STRING)
    /* run code for parsing the strings */
#elif defined (NO_PARSE_STRING)
    /* run code that doesn't parse the strings
#endif
    }

Upvotes: 0

Views: 958

Answers (3)

Khalos
Khalos

Reputation: 2373

You've included the ending bracket for the for loop in one of the conditionals

#else
  }
#endif

Should be

#else
   //Stuff
#endif
}

Upvotes: 2

Reese Moore
Reese Moore

Reputation: 11640

This is because if it is defined, you're going to not have the closing } which will be a syntax error.

Upvotes: 2

James McNellis
James McNellis

Reputation: 354979

You've mixed up the interleaving of the preprocessing directives with the start and end of the function body:

}
#endif

Should probably be

#endif
}

Upvotes: 7

Related Questions