C/C++ macro parameter containing dot (member access operator)

2.8k Views Asked by At

How can one use in C/C++ macro parameter containing dot (member access operator)?

Example:

#define M(obj,y) obj.y##x
struct S { struct {int x;} c; int x; };
S s;
s.c.x = 1;
s.x = 2;
M(s,)   // works, 2 (resolves to s.x)
M(s,c.) // error: pasting formed '.x', an invalid preprocessing token

How can one make M(s,c.) to resolve to s.c.x ?

Thank you for your help!

1

There are 1 best solutions below

1
On BEST ANSWER

The token pasting operator ## requires its two operands to be valid preprocessing tokens, and yields a single preprocessing token. It is often used to concatenate two identifiers into a single identifier.

What you are trying to do here is not token pasting. Instead, you are seeking to create expressions like s.x or s.c.x where the x part is always a single token. Therefore, the ## operator should not be used. Instead, you can just do this:

#define M(obj, y) obj.y x

When you try to use the ## operator, the preprocessor tries to combine the last token in the argument y with the token x. In c., the . is a token, so the result is .x, which is not a valid token. Rather, .x is only valid as a sequence of two tokens.