A trick using #if pre-processor

Posted by – February 13, 2006

I hit a small C++ grammar trick which I have never met before in my project. The problem is how to deal with the situation that two defined identifiers have the same compilation behavior. A simple solution to this is to write two same block code like this:

#ifdef  identifier1
#ifdef  identifier2
// do something thing
#endif
#endif

Doing this seems a little odd , and I finally write the code like below:

#if defined(identifier1) && defined(identifier2)
// do something
#endif

Similarly, if the situation is #ifndef, it can be written as below:

#if !defined(identifier1) && !defined(identifier2)
// do something
#endif

However the defined directive can only be used in an #if and an #elif directive, but nowhere else. The following code block shows an example like a “if…else if… else…” flow chart.

#if defined(ALICE)
alice();
#elif defined(BOB)
bob();
#else
printerror();
#endif

The function call to alice is compiled if the identifier ALICE is defined. If the identifier BOB is defined, the function call to bob is compiled. If neither identifier is defined, the call to printerror is compiled.

WeChatWhatsAppEvernoteLineInstapaperFacebookTwitterGoogle+LinkedInBaidu

2 Comments on A trick using #if pre-processor

  1. Zhu Xinquan says:

    nbysy,
    Thanks for your correction. I have modified the entry and welcome to come here and give me some advice again.

  2. nbysy says:

    第一段代码,第二个应该是 identifier2 吧?
    第二段代码,为什么要用 && 呢? 无论是用 ||还是&&, 我觉得其编译的结果都会和第一段不一样。
    第三段代码的解释,应该是:
    The function call to alice is compiled if the identifier ALICE is defined. If ALICE is not defined and the identifier BOB is defined, the function call to bob is compiled. If neither identifier is defined, the call to printerror is compiled.

Leave a Reply

Your email address will not be published. Required fields are marked *