Search code examples
c#c-preprocessoroperator-precedence

What is the precedence of operators in C# Preprocessor Directives?


If I have a piece of code written in C# wrapped in an #if directive, what (if any) precedence is applied to any boolean operators that might be used in that directive?

In other words:

#if DEBUG || MYTEST && PLATFORM_WINDOWS
// ... Some code here
#endif

Will that be simply evaluated left to right as

#if (DEBUG || MYTEST) && PLATFORM_WINDOWS

And similarly, would

#if PLATFORM_WINDOWS && DEBUG || MYTEST

Be evaluated as

#if (PLATFORM_WINDOWS && DEBUG) || MYTEST

Or is there some precedence order for && vs ||?

Edit: To be clear, I am well aware that I can run the code myself to test it, and I have. I'm looking for an answer that gives me something official - a reference to documentation or the like, which can give me a deeper understanding of the underlying mechanics of directives. I'd like to know if there is a specifically intended behaviour or if this is purely something that is undefined.


Solution

  • 2.5.2 Pre-processing expressions

    Evaluation of a pre-processing expression always yields a boolean value. The rules of evaluation for a pre-processing expression are the same as those for a constant expression (§7.19), except that the only user-defined entities that can be referenced are conditional compilation symbols

    7.19 Constant expressions

    The compile-time evaluation of constant expressions uses the same rules as run-time evaluation of non-constant expressions*, except that where run-time evaluation would have thrown an exception, compile-time evaluation causes a compile-time error to occur.

    So the same operator precedence applies to pre-processing expressions, constant expressions and runtime evaluation.

    7.3.1 Operator precedence and associativity

    (...)

    7.11 Logical AND &

    7.11 Logical XOR ^

    7.11 Logical OR |

    7.12 Conditional AND &&

    7.12 Conditional OR ||

    (...)

    From highest to lowest precedence.