C complex #define question

Oct 9, 2013 at 1:51pm
What does this statement do? I know ## concatenates and I know the converts macro parameters to string literals, but overall I'm not sure what this statement does. Any help would be appreciatede.



#define ADD_TOKEN_LIST(name) { "Xig" #name "token", Xig ## name ## tokens }

Oct 9, 2013 at 1:57pm
closed account (NUj6URfi)
Defines a statement.
Oct 9, 2013 at 2:05pm
I know it defines a statement, but I don't understand the statement.
Oct 9, 2013 at 2:49pm
Not very helpful, toad... >_>


Anyway... to answer your question.

#name takes the parameter name and turns it to a string literal.
## takes two separate tokens and combines them into one.

For example... if you were to say:
 
ADD_TOKEN_LIST(foo)


That would expand to the below:

1
2
3
4
5
6
7
8
{ "Xig" "foo" "token", Xigfootokens }
          ^                 ^
          |                 |
          |             ## name ##:  name gets replaced with foo
          |             then the ##s make the foo 'join' with the tokens around it
          |
          |
          #name takes the given name 'foo' and turns it into a string literal 



Also... in C and C++... two string literals that are declared next to each other like that are automatically joined. This is true everywhere, not just in macros.

So "Xig" "foo" "token" essentially becomes "Xigfootoken"


Therefore....

1
2
3
4
5
ADD_TOKEN_LIST(foo)

// expands to...

{ "Xigfootoken", Xigfootokens }




EDIT:

Usage of this is likely to build an array. IE, it's probably used like this:

1
2
3
4
5
6
struct SomeStruct[] = 
{
ADD_TOKEN_LIST(foo),
ADD_TOKEN_LIST(bar),
ADD_TOKEN_LIST(baz)
};
Last edited on Oct 9, 2013 at 2:51pm
Oct 9, 2013 at 3:11pm
Thanks, and have a great day!
Topic archived. No new replies allowed.