Sign in to follow this  
DrTwox

Using strings in macros

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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".

Share this post


Link to post
Share on other sites
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"));

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this