Search code examples
cc-preprocessorpreprocessor-directivecomma-operator

Comma-Operator in Preprocessor-Directives


This is a question for deeper understanding.

Let's say I have the following code:

#define DEF 1,2,3
#if (DEF > 3)
#endif

If I am right the if should always be true, as 1 and 2 are Expressions that have no affect and only 3 will be checked. (This should at least be true in normal C/C++-code)

But is that right or would there be any Reason why I should think about 1 and 2, too? I saw it in some code and I am not really sure if this could have any sense or affect.


Solution

  • Your example code is not strictly conforming.

    From C11, 6.10.1 par. 3 (Conditional inclusion, Semantics):

    Preprocessing directives of the forms

    # if constant-expression new-line groupopt

    # elif constant-expression new-line groupopt

    check whether the controlling constant expression evaluates to nonzero

    However 6.6 par. 3 (Constant expressions, Constraints) says:

    Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.115)

    Footnote 115 is:

    The operand of a sizeof or _Alignof operator is usually not evaluated (6.5.3.4).