C programming supports two special preprocessor directive for string operations. Stringize (#) and token pasting (##) are C preprocessor string manipulation operators.
In previous article we learned about basic and conditional preprocessor directives in C language. In this article we will move further and learn string manipulation preprocessor operators.
C programming supports two string manipulation operators.
- Stringize operator (#)
- Token pasting operator (##)
Stringize operator (#)
We use stringize operator in C to convert a token to string. It transforms the macro parameter to string. It causes the macro parameter to enclose in double quoted string.
Syntax:
#define MACRO_NAME(param) #paramExample:
#include <stdio.h>
// Macro definition with stringize operator
#define PRINT(msg) #msg
int main()
{
printf(PRINT(C Programming in Codeforwin));
return 0;
}Output:
C Programming in CodeforwinNote: In the above code printf() function accepts a pointer to constant character (string). However, we are passing a macro to the printf() function. The macro executes prior to the compilation of program. In the process of macro expansion during preprocessing, the C preprocessor expands PRINT(C Programming in Codeforwin) to "C Programming in Codeforwin". After which our printf() function is expanded to printf("C Programming in Codeforwin");.
Token pasting operator (##)
Token pasting operator (##) combines or concatenates tokens together. The ## operator concatenates two tokens. During macro expansion parameter next to ## is combined with the parameter before ## and returned as a single token.
Read more about What are tokens in programming?
Syntax:
#define MACRO_NAME(param1, param2) param1##param2Where MACRO_NAME is an identifier i.e. name of the macro. It accepts two param param1 and param2 and returns concatenation of param1 and param2.
Note: It is not necessary to pass two params to macro for token pasting. You can pass any number of parameter.
Example:
#include <stdio.h>
// Macro definition with token pasting
#define CONCAT(a, b) a##b
int main()
{
printf("CONCAT(10, 20) = %d\n", CONCAT(10, 20));
return 0;
}Output:
CONCAT(10, 20) = 1020Feel free to drop your queries and suggestions.
Happy coding 😉