Lajos
Lajos

Reputation: 45

The precedence of preprocessor operator "defined"?

I'm working on a c preprocessor and have found that, since "defined" is a preprocessor-only operator, its precedence level is never listed among the other c operators. Since it is unary and logical, I'd put it on the 2nd level, but...

Does anyone know the exact answer?

Upvotes: 3

Views: 572

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222923

C 2018 6.10.1 1 says:

The expression that controls conditional inclusion shall be an integer constant expression except that… it may contain unary operator expressions of the form “defined identifier” or “defined ( identifier )”… [Note: The text in quotes here is offset display text in the original.]

The phrase “unary operator expression” refers to 6.5.3 (“Unary operators”), a subsection of 6.5 (“Expressions”). Thus, defined behaves like any of the other unary operators.

However, note that the operand must be an identifier. It cannot be the general unary-expression or cast-expression that most normal operators accept. It is those unary-expression or cast-expression symbols that bring higher-precedence operators into the grammar for unary expressions. This means something like #if defined x++ is not permitted (even prior to consideration of whether ++ may appear in an integer constant expression), so there is never any other option. “defined identifier” never appears with any higher-precedence operator adjacent to the identifier.

Upvotes: 2

dbush
dbush

Reputation: 224072

An #if directive is immediately followed by a constant experssion. Any defined operators are evaluated first before the rest of the constant expression is evaluated.

Section 6.10.1p4 of the C standard states:

Prior to evaluation, macro invocations in the list of preprocessing tokens that will become the controlling constant expression are replaced (except for those macro names modified by the defined unary operator), just as in normal text. If the token defined is generated as a result of this replacement process or use of the defined unary operator does not match one of the two specified forms prior to macro replacement, the behavior is undefined. After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers
(including those lexically identical to keywords) are replaced with the pp-number 0 , and then each preprocessing token is converted into a token. The resulting tokens compose the controlling constant expression which is evaluated according to the rules of 6.6. ...

The references section 6.6 dictates the semantics of Constant Expressions

Upvotes: 0

Related Questions