It is often useful to merge two tokens into one while expanding macros. This is called token pasting or token concatenation. The {{##}} preprocessing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ## operator are combined into a single token, which replaces the {{##}} and the two original tokens in the macro expansion \[[FSF 05|AA. C References#FSF 05]\]. |
Token pasting is most useful when one or both of the tokens comes from a macro argument. If either of the tokens next to an ##}}is a parameter name, it is replaced by its actual argument before {{## executes. The actual argument is not macro-expanded first.
#define JOIN(x, y) JOIN_AGAIN(x, y) #define JOIN_AGAIN(x, y) x ## y |
JOIN(x, y) calls JOIN_AGAIN(x, y) so that, if x or y is a macro, they are expanded before the ## operator pastes them together.
Note also that macro parameters cannot be individually parenthesized when concatenating tokens using the {{##}} operator, converting macro parameters to strings using the {{#}} operator, or concatenating adjacent string literals. This is an exception to \[[PRE01-A. Use parentheses within macros around parameter names]\]. |
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
DCL03-A |
1 (low) |
1 (unlikely) |
1 (high) |
P1 |
L3 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[FSF 05|AA. C References#FSF 05]\] Section 3.5, "[Concatenation|http://gcc.gnu.org/onlinedocs/gcc-4.3.0/cpp/Concatenation.html#Concatenation]" \[Saks 08\] Dan Saks, Stephen C. Dewhurst. Presentation. Sooner Rather Than Later: Static Programming Techniques for C++. \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.10.3, "Macro replacement," Section 6.10.3.3, "The ## operator," and Section 6.10.3.4, "Rescanning and further replacement" |
PRE04-A. Do not reuse a standard header file name 01. Preprocessor (PRE) PRE06-A. Enclose header file in an inclusion sandwich