简体   繁体   中英

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

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!

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 sx 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM