PREPROCESSOR: Multiple expansions.

N

nobrow

(This is a contrived example)

With the following preprocessor lines:

#define SIZEOF_mytype 4

#define hton4b htonl

#define OUT(TYPE, VAR) \
OUT1(SIZEOF_ ## TYPE, VAR)

#define OUT1(SIZE, VAR) \
hton ## SIZE ## b(VAR)

I type:

OUT(mytype, t)

and want to get:

htonl(t)

but actually get:

htonSIZEOF_mytypeb(t)

I tried various intermediate macros to catenate SIZEOF_ and TYPE to try
get it to convert to 4 but the closest I have gotten is:

hton 4 b(t)

Whats the trick?

Thanks.
 
A

Ancient_Hacker

well, you're pushing the non-barfing limits of macro usage, but, ok,

does it work any better if you take out the spaces around the ##'s?
 
N

nobrow

Ancient_Hacker said:
well, you're pushing the non-barfing limits of macro usage, but, ok,

does it work any better if you take out the spaces around the ##'s?

I did as it happens (spaces surrounding glue have no effect as far as I
can see).

Calm prevailed and I went through it slowly and carefully, resulting in
the following which behaves as expected.

#define SIZEOF_mytype 4

#define hton4b htonl

#define CAT(A, B) A##B

#define OUT2(ARG, VAR) \
CAT(hton, ARG)

#define OUT1(SIZE, VAR) \
OUT2(CAT(SIZE,b(VAR)), VAR)

#define OUT(TYPE, VAR) \
OUT1(SIZEOF_##TYPE, VAR)

(Incidentally, the result is the same when using "A ## B" and "SIZEOF_
## TYPE").

Thanks for the reply anyway.
 
A

Ancient_Hacker

This works:


#define SIZEOF_mytype 4

#define hton4b htonl

#define OUT(TYPE, VAR) OUT1(SIZEOF_##TYPE, VAR)

#define OUT1(SIZE,VAR) expand(hton,SIZE,VAR)

#define expand(x,y,z) x##y##b(z)


OUT(mytype, t)
 
N

nobrow

Ancient_Hacker said:
This works:


#define SIZEOF_mytype 4

#define hton4b htonl

#define OUT(TYPE, VAR) OUT1(SIZEOF_##TYPE, VAR)

#define OUT1(SIZE,VAR) expand(hton,SIZE,VAR)

#define expand(x,y,z) x##y##b(z)


OUT(mytype, t)

Thanks.
 

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

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top