As mentioned in many of my previous questions, I'm working through K&R, and am currently into the preprocessor. One of the more interesting things — something I never knew before from any of my prior attempts to learn C — is the ##
preprocessor operator. According to K&R:
The preprocessor operator
##
provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a##
, the parameter is replaced by the actual argument, the##
and surrounding white space are removed, and the result is re-scanned. For example, the macropaste
concatenates its two arguments:
#define paste(front, back) front ## back
so
paste(name, 1)
creates the tokenname1
.
How and why would someone use this in the real world? What are practical examples of its use, and are there gotchas to consider?
Here's a gotcha that I ran into when upgrading to a new version of a compiler:
Unnecessary use of the token-pasting operator (
##
) is non-portable and may generate undesired whitespace, warnings, or errors.When the result of the token-pasting operator is not a valid preprocessor token, the token-pasting operator is unnecessary and possibly harmful.
For example, one might try to build string literals at compile time using the token-pasting operator:
On some compilers, this will output the expected result:
On other compilers, this will include undesired whitespace:
Fairly modern versions of GCC (>=3.3 or so) will fail to compile this code:
The solution is to omit the token-pasting operator when concatenating preprocessor tokens to C/C++ operators:
The GCC CPP documentation chapter on concatenation has more useful information on the token-pasting operator.