开发者

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

开发者 https://www.devze.com 2023-01-23 16:26 出处:网络
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.

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 (P开发者_JAVA百科ARSE_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
    }


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

}
#endif

Should probably be

#endif
}


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


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

#else
  }
#endif

Should be

#else
   //Stuff
#endif
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号