Preprocessor define concatenation

M

michael.martin

Hi,

I am wondering if something like this is possible?

#define COLON ":"
#define PERIOD "."

#define WORD "word"

#define WORD_COLON WORD+COLON
#define WORD_PERIOD WORD+PERIOD

....

I know the above is incorrect syntax. But is there a way to
concatenate the above strings in some way? I would rather not have to
define WORD_COLON as "word:" and WORD_PERIOD as "word.". I would like
to be able to change the value of WORD, with just modifying one
constant, rather than modifying all 3, as I am doing this on a much
larger scale.

Thanks for any help,
mike martin
 
J

Joona I Palaste

(e-mail address removed) scribbled the following:
I am wondering if something like this is possible?
#define COLON ":"
#define PERIOD "."
#define WORD "word"
#define WORD_COLON WORD+COLON
#define WORD_PERIOD WORD+PERIOD

I know the above is incorrect syntax. But is there a way to
concatenate the above strings in some way? I would rather not have to
define WORD_COLON as "word:" and WORD_PERIOD as "word.". I would like
to be able to change the value of WORD, with just modifying one
constant, rather than modifying all 3, as I am doing this on a much
larger scale.

The C compiler concatenates any adjacent string literals into a single
string literal. Therefore
#define WORD_COLON WORD COLON
#define WORD_PERIOD WORD PERIOD
should do the trick.
 
Y

Yan

Joona said:
(e-mail address removed) scribbled the following:



The C compiler concatenates any adjacent string literals into a single
string literal. Therefore
#define WORD_COLON WORD COLON
#define WORD_PERIOD WORD PERIOD
should do the trick.
you need the ## operator

i.e.:

#define concat(a, b) a ## b

and if you call it with:

concat(12,45), the pre-processor will replace it with 1245

-yan
 
K

Keith Thompson

Yan said:
you need the ## operator

i.e.:

#define concat(a, b) a ## b

and if you call it with:

concat(12,45), the pre-processor will replace it with 1245

The OP was trying to concatenate string literals. The ## operator is
valid only if the result is a single token. concat(12,45) does yield
the single token 1245, but concat("word",":") yields "word"":", which
is not a single token.

Joona was correct. Implicit string literal concatenation will do what
the OP wants; the ## operator (useful though it is for other things)
will not.
 

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,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top