简体   繁体   中英

Using name of macro from within macro in C

#define V_M1 10
#define A_M1 60
#define V_M2 15
#define A_M2 56

#define M1 { V_M1, A_M1 }
#define M2 { V_M2, A_M2 }
int m1[]=M1, m2[]=M2;

Is there a way to simplify the definition of the M1 and M2 macros so that I don't have to repeat their names inside (source of errors in my case due to the actual complexity of the macros) ? Something like:

#define M1 { V_MyOwnName, A_MyOwnName }
#define M2 { V_MyOwnName, A_MyOwnName }

Add a level of indirection with a function-like macro

#define EXPAND(name) { V_##name, A_##name }
#define M1 EXPAND(M1)
#define M2 EXPAND(M2)

The ## is the token concatenation operator, that takes V and whatever you pass as name and glues them to form a single token. If the result is another macro, it's expanded further.

Macros like these are often questionable practice. Consider grouping your values in const structs or similar, for better program design.

That being said, everything in C is possible if you throw enough evil macros on it. Given no other choice but to use macros, I would do something like this:

#define M(n) { V_M ## n, A_M##n }
int m1[]=M(1), m2[]=M(2);

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