It is necessary to understand how macro replacement works in C, particularly in the context of concatenating tokens using the ##
operator and converting macro parameters to strings using the #
operator.
Concatenating Tokens
The ##
preprocessing operator is used to merge two tokens into one while expanding macros. This is called token pasting or token concatenation. 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 2005].
Token pasting is most useful when one or both of the tokens come 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.
Stringification
Parameters are not replaced inside string constants, but you can use the #
preprocessing operator instead. When a macro parameter is used with a leading #
, the preprocessor replaces it with the literal text of the actual argument, converted to a string constant [FSF 2005].
...
The following definition for static_assert()
from DCL03-C. Use a static assertion to test the value of a constant expression uses the JOIN()
macro to concatenate the token assertion_failed_at_line_
with the value of __LINE__
.:
Code Block |
---|
#define static_assert(e) \ typedef char JOIN(assertion_failed_at_line_, __LINE__) \ [(e) ? 1 : -1] |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard | PRE05-CPP. Understand macro replacement when concatenating tokens or performing stringification |
Bibliography
[FSF 2005] | Section 3.4, "Stringification" Section 3.5, "Concatenation" |
[Saks 2008] |
...