2
#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 }

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And going a bit further, OP could eliminate the M1 and M2 macros, and define int m1[] = EXPAND(M1), m2[] = EXPAND(M2);.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.