Reputation: 325
From what I have read I understand that #
operator is used with a parametric macro to convert it's parameter to a string and ##
is used to join two parameters or a parameter with some other identifier (Correct me if my understanding is wrong).
But how can I use both #
and ##
operator together? I tried it by doing:
#define str(n) #n ## #n
I thought then
printf("%s",str(Hello))
will be expanded as
printf("%s", "Hello""Hello")
And as adjacent strings are joined automatically to make one string in C so, this will lead to printf("%s", "HelloHello")
and output will beHelloHello
. But the story was different, it throws an error:
pasting "hello" and "hello" does not give a valid preprocessing token
Please explain me how these parametric macros with #
and ##
operator are expanded.
Upvotes: 0
Views: 57
Reputation: 170239
##
"joining two parameters" is a vast oversimplification. This operator joins tokens. And the result must be a single valid token. Two string literal tokens cannot be token pasted into a single token.
Furthermore, string literal concatenation is handled at a later translation phase. So an obvious fix to your macro is to not use ##
at all.
#define str(n) #n #n
But if you really want to use both, then you need to token paste before stringifying. And do that via an intermediate macro expansion.
#define str(n) str_(n ## n)
#define str_(nn) #nn
Upvotes: 3