Pregunta

(I am working on a SDK wherein I have the code of the particular SDK in reference and I am not able to trace out the flow of the program.)

What does

#if defined (AR7x00)

mean? Specifically, what is the purpose of parentheses in a such a preprocessor operator?

¿Fue útil?

Solución

These three preprocessor directives:

#if defined (AR7x00)

#if defined AR7x00

#ifdef AR7x00

all mean exactly the same thing: that the following code is to be processed only if the macro AR7x00 is currently defined.

The #ifdef ... directive is simply a convenient alternative to #if defined .... There's also a #ifndef ... directive; #ifndef FOO is equivalent to #if ! defined FOO.

As for the parentheses, the syntax for the defined operator allows for either an identifier, or an identifier in parentheses, with no difference in meaning. I'm not entirely sure why the parentheses are optional; I suspect it's just historical. (The language reference in the 1978 first edition of K&R doesn't mention the defined operator. The second edition shows both forms, with and without parentheses.)

Strictly speaking, these are not grouping parentheses of the kind you see in ordinary expressions; they're specifically part of the syntax of the defined operator, which can only be used in preprocessor #if directives. In particular, this:

#if defined ((AR7x00))

is a syntax error.

Otros consejos

I think the parantheses are more important when using multiple conditionals in the preprocessor. For instance the following conditional expression

#if  defined( foo )  || defined( bar )
#error SOME PROBLEM
#endif

evaluates differently in my gnu-arm-gcc environment than this one

#if defined foo || defined bar
#error SOME PROBLEM
#endif

The first example does what I expect, while the other doesn't seem to ever match regardless of if the tokens "foo" and/or "bar" are #defined.

The gnu.org online docs state that you can use defined with or without parentheses.

From the MSDN entry for #if:

You can also group symbols and operators with parentheses.

The parentheses don't do anything other than group symbols and operators together to modify precedence.

C11, 6.10.1 Conditional inclusion, 5:

Preprocessing directives of the forms

# ifdef identifier new-line groupopt

# ifndef identifier new-line groupopt

check whether the identifier is or is not currently defined as a macro name. Their conditions are equivalent to #if defined identifier and #if !defined identifier respectively.

Here we see that parentheses are not required.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top