Stringize (#) and token pasting (##) operator in C language

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) #param

Example:

#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 Codeforwin

Note: 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.

Syntax:

#define MACRO_NAME(param1, param2) param1##param2

Where 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) = 1020

Feel free to drop your queries and suggestions.

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>