Using strings in macros

Started by
2 comments, last by DrTwox 15 years, 5 months ago
Hi all. I'm trying to create a macro in C...

#define DB_QUERY_ALBUMS(a) "SELECT DISTINCT album FROM music WHERE artist=\""#a"\" ORDER BY year;"
Where (a) is the name of the artist to substitute into the macro. I call the macro like this: list = db_query(DB_QUERY_ALBUMS_BY_ARTIST(Ministry)); Using "gcc -E" I can see the macro expands to: "SELECT DISTINCT album FROM music WHERE artist=\"""Ministry""\" ORDER BY year; Which is obviously wrong, as there are too many quotes! If I drop the hash from the macro it expands to: "SELECT DISTINCT album FROM music WHERE artist=\""Ministry "\" ORDER BY year;" ...still too many quotes, and a null byte terminator is added. I've tried reading a few online texts about the C preprocessor, but they seem to jump from newbie programmer to hardcore macro-foo without any steps in between! What's the correct way of doing this?
Advertisement
What you've already got should just work. It doesn't matter that you've got too many quotes, since adjacent string literals in C will automatically concatenate.

eg. "abc" "def" is the same as "abcdef".
NextWar: The Quest for Earth available now for Windows Phone 7.
As Sc4Freak proposed, try:

#define DB_QUERY_ALBUMS(a) "SELECT DISTINCT album FROM music WHERE artist=\"" a "\" ORDER BY year;"

list = db_query(DB_QUERY_ALBUMS_BY_ARTIST("Ministry"));
I was thinking any extra quotes would confuse the sql query, but it works just fine.

Thank you!

This topic is closed to new replies.

Advertisement