44

I have a function which accepts one argument of type char*, like f("string");
If the string argument is defined by-the-fly in the function call, how can macros be expanded within the string body?

For example:

#define COLOR #00ff00
f("abc COLOR");

would be equivalent to

f("abc #00ff00");

but instead the expansion is not performed, and the function receives literally abc COLOR.

In particular, I need to expand the macro to exactly \"#00ff00\", so that this quoted token is concatenated with the rest of the string argument passed to f(), quotes included; that is, the preprocessor has to finish his job and welcome the compiler transforming the code from f("abc COLOR"); to f("abc \"#00ff00\"");

1
  • 2
    The preprocessor does not touch string literals. Commented Oct 18, 2012 at 16:11

2 Answers 2

58

You can't expand macros in strings, but you can write

#define COLOR "#00ff00"

f("abc "COLOR);

Remember that this concatenation is done by the C preprocessor, and is only a feature to concatenate plain strings, not variables or so.

Sign up to request clarification or add additional context in comments.

4 Comments

Is this equivalent to passing 2 arguments to f() ?
@davide no, putting two string literals next to each other makes the C compiler concatenate them.
No, the strings will be concat by the compiler. At compile time, the string will result in "abc #00ff00"
I believe the concatenation "abc ""#00ff00" to "abc #00ff00"is performed by compiler instead of preprocessor. gcc.gnu.org/onlinedocs/cpp/Stringification.html Notice in the second paragraph: The preprocessor will replace the stringified arguments with string constants. The C compiler will then combine all the adjacent string constants into one long string.
4
#define COLOR "#00ff00"
f("abc "COLOR);

1 Comment

I think it's worth noting that this works because C "automatically concatenates" two strings if they appear without anything in between.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.