Reputation: 99418
From The C Programming Language, by KRC
After
#define cat(x, y) x ## y
the call
cat(var, 123)
yieldsvar123
. However, the callcat(cat(1,2),3)
is undefined: the presence of##
prevents the arguments of the outer call from being expanded. Thus it produces the token stringcat ( 1 , 2 )3
and)3
(the catenation of the last token of the first argument with the first token of the second) is not a legal token.If a second level of macro definition is introduced,
#define xcat(x, y) cat(x,y)
things work more smoothly;
xcat(xcat(1, 2), 3)
does produce123
, because the expansion ofxcat
itself does not involve the##
operator.
What is the property of ##
that makes the difference between the two examples?
Why is the inner cat(1,2)
in the first example not expanded, while the inner xcat(1,2)
in the second example is?
Thanks!
Upvotes: 3
Views: 636
Reputation: 6063
It is one of the (not-so-well-known) characteristics of the macro ##
operator that it inhibits further expansion of its arguments (it just considers them plain strings). An excerpt from the gcc pre-processor docs:
...As with stringification, the actual argument is not macro-expanded first...
That is, arguments to ##
are not expanded.
By implementing the additional indirection using your xcat
macro you are working around the problem (A process that is called the argument prescan is jumping in and actually evaluates the resulting string twice)
Upvotes: 1