2

In the C excerpt below, is SUPPORT_MULTI_DNS_SERVER executed only when ProductName is defined?

#ifdef <ProductName>
 //do things here
#ifdef SUPPORT_MULTI_DNS_SERVER
 //do things here
#endif
 //do things here
#endif

Edit: SWE780 changed to product name.

1
  • 3
    There is no SWE780 in the code you show. The code inside the inner #ifdef (the second one) is kept in the program if and only of both the outer (first) #ifdef and the inner #ifdef are satisfied. Commented Sep 17, 2018 at 3:03

2 Answers 2

4

Pre-processor conditionals will nest. For example, with:

#ifdef XYZZY
    int a;
    #ifdef PLUGH
        int b;
    #endif
    int c;
#endif

The b variable will exist only if both XYZZY and PLUGH are defined. The a and c variables depend only on XYZZY.

From the C11 standard, section 6.10.1 Conditional inclusion /6:

Each directive’s condition is checked in order. If it evaluates to false (zero), the group that it controls is skipped: directives are processed only through the name that determines the directive in order to keep track of the level of nested conditionals.

This "group" is the entire section, including all sub-groups. In the example given above, the XYZZY group is everything between #ifdef XYZZY and the corresponding #endif.

3

That is how conditional inclusions work. The ifdef nested within another ifdef is included only if the first ifdef evaluates to true. In your case:

#ifdef SUPPORT_MULTI_DNS_SERVER
 //do things here
#endif

is included only if #ifdef <ProductName> is true (I am assuming <ProductName> is SWE780).

From the C Committee draft (N1570):

6.10.1 Conditional inclusion
...

  1. Each directive’s condition is checked in order. If it evaluates to false (zero), the group that it controls is skipped: directives are processed only through the name that determines the directive in order to keep track of the level of nested conditionals; the rest of the directives’ preprocessing tokens are ignored, as are the other preprocessing tokens in the group. Only the first group whose control condition evaluates to true (nonzero) is processed. If none of the conditions evaluates to true, and there is a #else directive, the group controlled by the #else is processed; lacking a #else directive, all the groups until the #endif are skipped.
2
  • Just to clarify, can a #ifdef be left hanging without a #endif? Like in a regular if-else statements, curly bracket is not neccessary if it's just a line.
    – Firzanah
    Commented Sep 17, 2018 at 9:23
  • 2
    No, this is not possible. Each #ifdef should have a corresponding #endif. Otherwise there will be a compilation error stating, error: unterminated #ifdef
    – P.W
    Commented Sep 17, 2018 at 10:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.