So here are some macros I have created:
#define MODULE_NAME moduleName
#define MODULE_STRUCT MODULE_NAME ## _struct
#define MODULE_FUNCTION(name) MODULE_NAME ## _ ## name
After those definitions, I would like the following expansions to happen:
MODULE_STRUCT --> moduleName_struct
MODULE_FUNCTION(functionName) --> moduleName_functionName
However, when I add the token pasting operators, expansion of MODULE_NAME within MODULE_FUNCTION and MODULE_STRUCT no longer happens... It seems to consider MODULE_NAME as a literal string when pasting them together.
Is there a way around this?
The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.
The LENGTH and BREADTH are called the macro templates. The values 10 and 20 are called macro expansions. When the program run and if the C preprocessor sees an instance of a macro within the program code, it will do the macro expansion. It replaces the macro template with the value of macro expansion.
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 then replaces the ' ## ' and the two original tokens in the macro expansion.
Here also we have to include ellipsis, The '__VA_ARGS__' is used to handle variable length arguments. Concatenation operator '##' is used to concatenate the variable arguments. In this example, the Macro will take variable length argument like the printf() or scanf() function.
In C the operands of the token pasting operator ##
are not expanded.
You need a second level of indirection to get the expansion.
#define CAT(x, y) CAT_(x, y)
#define CAT_(x, y) x ## y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With