Parzival
Parzival

Reputation: 623

C macro to paste tokens

I have a macro defined as below

#define X_T_a(b)            b->a

b = pointer to a struct, a = field in that struct

I want to define another macro T(a,b) that resolves to X_T_a(b)

Should I use

#define T(a, b)             X_T_##a(b)

or

#define T(a,b)   X_T(a,b)
#define X_T(a,b)   X_T_##a(b)

both works for the input I use.. But I am not much familiar with using macros. I want to understand if some input can break these..

Upvotes: 1

Views: 125

Answers (1)

user694733
user694733

Reputation: 16047

Single macro version doesn't work with macro symbols.

For example, say you have:

#define MACRO_OBJECT   realObject
#define MACRO_MEMBER   realMember
T(MACRO_OBJECT, MACRO_MEMBER)

You want this to expand to X_T_realObject(realMember).

If you use your first version, you will get X_T_MACRO_OBJECT(realMember), because concatenation operator ## will work before MACRO_OBJECT is expanded to realObject.

Upvotes: 1

Related Questions