C Preprocessor - Cascaded Macros

M

Michael Blackney

I've been looking into cascaded macros and I can't seem to find if
what I'm doing is portable. I want to do something like:

#define THREE_ONES 1,1,1
#define ONE_TWO_THREE 1,2,3

#define JOIN_LISTS(a,b) JOIN_LISTS_PROCESSED(a,b)
#define JOIN_LISTS_PROCESSED(a1,b1,c1,a2,b2,c2) a1+a2,b1+b2,c1+c2

so that the statement:

{ JOIN_LISTS(THREE_ONES,ONE_TWO_THREE) },

will expand (one the first preprocessor pass) to:

{ JOIN_LISTS_PROCESSED(1,1,1,1,2,3) },

then expand on the second pass to:

{ 1+1, 1+2, 1+3 },

On my compiler (DJGPP) it works just fine - but is it portable? Do
all preprocessors use a similar replacement order?
 
C

Chris Barts

I've been looking into cascaded macros and I can't seem to find if
what I'm doing is portable. I want to do something like:

#define THREE_ONES 1,1,1
#define ONE_TWO_THREE 1,2,3

#define JOIN_LISTS(a,b) JOIN_LISTS_PROCESSED(a,b)
#define JOIN_LISTS_PROCESSED(a1,b1,c1,a2,b2,c2) a1+a2,b1+b2,c1+c2

All of these definitions look portable. For maximum utility, you should
put in a lot more parentheses, like so:

(a1)+(a2),(b1)+(b2),(c1)+(c2)

Why? So you can have lists like this:
JOIN_LISTS_PROCESSED(x+5,2+3/2,5-6,4-23,5&6,7^2)
so that the statement:

{ JOIN_LISTS(THREE_ONES,ONE_TWO_THREE) },

will expand (one the first preprocessor pass) to:

{ JOIN_LISTS_PROCESSED(1,1,1,1,2,3) },

then expand on the second pass to:

{ 1+1, 1+2, 1+3 },

On my compiler (DJGPP) it works just fine - but is it portable? Do
all preprocessors use a similar replacement order?

I can't think of any reason a conforming compiler would misparse your
headers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top