user2268152
user2268152

Reputation: 108

How to control C Macro Precedence

#define VAL1CHK 20

#define NUM 1

#define JOIN(A,B,C) A##B##C

int x = JOIN(VAL,NUM,CHK);

With above code my expectation was

int x = 20;

But i get compilation error as macro expands to

int x = VALNUMCHK; // Which is undefined

How to make it so that NUM is replaced first and the JOIN is used?

Upvotes: 2

Views: 138

Answers (1)

M Oehm
M Oehm

Reputation: 29126

You can redirect the JOIN operation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments:

#define VAL1CHK 20
#define NUM 1
#define JOIN1(A, B, C) A##B##C
#define JOIN(A, B, C) JOIN1(A, B, C)

int x = JOIN(VAL,NUM,CHK);

This technique is often used with the pasting and stringification operators in macros.

Upvotes: 5

Related Questions