tags:

views:

944

answers:

5

Is there a way to get the C++ pre processor to expand a #define'ed value into a string literal?
for example:

#define NEW_LINE '\n'
Printf("OutputNEW_LINE"); //or whatever

This looks to me like it should be possible as it's before compilation?
Or is there a better design pattern to achieve this kind of behaviour (without resorting to runtime fixes like sprintf)? Thanks

EDIT i understand that #define's can be evil, but for arguments sake...

ADDITIONAL Does anyone have any criticism of this approach?

+3  A: 

If I remember correctly it is

Printf("Output" NEW_LINE);
Thomas Freudenberg
So this will be expanded at build time not via Printf's formating facility?
Adam Naylor
Yes, the C compiler will automatically concatenate adjacent string literals, although the #define should define NEW_LINE as "\n" and not '\n' for that to work, I think.
Joey
Why the downvote, just because of uppercase printf?
Kosi2801
I don't understand the downvote either
Thomas Freudenberg
+1 to counteract the unwarranted downvote. (It wasn't my downvote, but perhaps it was because the code won't work with #define NEW_LINE '\n' (with single quotes) as given in Adam's question. Harsh but a possibility.)
RichieHindle
+8  A: 

This will do it:

#define NEW_LINE "\n"         // Note double quotes
Printf("Output" NEW_LINE);

(Technically it's the compiler joining the strings rather than the preprocessor, but the end result is the same.)

RichieHindle
Thanks for the quotes comment
Adam Naylor
Everydays a school day!
Adam Naylor
+2  A: 

You can do the following.

#define NEW_LINE "\n"
printf("Output" NEW_LINE);
avakar
A: 

Well....

printf("Output%s", NEW_LINE);
Domas Mituzas
This would be a runtime fix
Adam Naylor
exactly, but much easier to maintain in the long term :)
Domas Mituzas
mmmm... Not really, you'd still have to recompile everything if the #define changes and the missing comma should be no cause of trouble if something in the text changes, as you can still add placeholders and variables without breaking something. At least in my opinion.
Kosi2801
+1  A: 
#define NEW_LINE "\n"
printf("Output" NEW_LINE); //or whatever

should do the trick.

Kosi2801