#define DB_QUERY_ALBUMS(a) "SELECT DISTINCT album FROM music WHERE artist=\""#a"\" ORDER BY year;"
Using strings in macros
Hi all.
I'm trying to create a macro in C...
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?
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".
eg. "abc" "def" is the same as "abcdef".
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"));
#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"));
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement