Question

Is it possible to define a constant such as foo.bar via

#define foo.bar 42

When I try the above foo is expanded to .bar 42. Is there any way to escape the period or otherwise work around this?

Était-ce utile?

La solution

No . is not allowed in macro names since they are identifiers and identifiers are not allowed to include a .. We can see this by going to draft C99 standard section 6.10 Preprocessing directives which includes the following grammar:

# define identifier replacement-list new-line
# define identifier lparen identifier-listopt ) replacement-list new-line
# define identifier lparen ... ) replacement-list new-line
# define identifier lparen identifier-list , ... ) replacement-list new-line
         ^^^^^^^^^^

and section 6.4.2 Identifiers covers what is a valid identifier.

Autres conseils

No, the period character is not permitted in C preprocessor macro names.

However, in this case you can achieve a similar effect without using the preprocessor:

static struct { int bar; } foo = {42};

In C, macro name must be valid identifier, which means you cannot use . in your macro name.

As Greg says, the period character is not allowed in a macro name. However, macros are tricky. It is tempting to define foo to enter some intermediate state, and bar to resolve that state and perhaps generate 42.

#define foo RESOLVE_STATE(
#define bar , 42 )
#define RESOLVE_STATE( DOT, RESOLUTION ) RESOLUTION

Unfortunately, the intermediate state has unfavorable semantics. It accepts macro arguments until it finds a matching right parenthesis. But the arguments are not expanded, so the parenthesis must occur literally. You could make it work with the input foo.bar) but that's not very useful.

To be clear, this is a proof of impossibility.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top