dargaud
dargaud

Reputation: 2581

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 }

Upvotes: 2

Views: 70

Answers (2)

Lundin
Lundin

Reputation: 215360

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);

Upvotes: 1

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.

Upvotes: 6

Related Questions