Token Pasting Operator in c, you should know

Token Pasting Operator in c

Token Pasting Operator is sometimes called “merging” operator. It is used to merge two valid token that is also the reason it is called token concatenation.

In C language, the ## pre-processing operator performs token pasting. At the time of macro expanding two valid taken combined to each other and create a valid token.

See the use of token pasting operator in below code,

In below code, I am concatenating var with a numeric number. If a newly created token is valid, you will not get any error or warning.

Output: 10 ,20,30

In below code, var4 is not declared. if I compile the code, I will get the error.

token Pasting operator in c

If you want to learn more about the c language, here 10 Free days C video course for you.

C tutorial


If you perform ‘token pasting’ on tokens that does not make a valid token, then you should avoid the token pasting.

For example,
if you concatenate var and + together, then it becomes var+ which has no meaning. So if you perform ‘token pasting’ on var and +, the compiler gives you an error or warning.

token Pasting operator

In token pasting, it is not necessary both tokens come from the macro body. It can be possible only one token comes from the macro body. When you pass an argument in the macro body then it replaces with parameter name before executing ‘##’.

Generally, token pasting operator is beneficial when one or more than two tokens come from the macro body. In below example code, you can see how we can use token pasting operator in different ways.

Output: 8,9,10,11

Some library uses token pasting operator to create multiple variables at once. This technique saves the time. See the below example code, where I am creating 5 variable using the single macro body.

Output: 10,11,12,13,14

Using the token pasting operator, we can also run a program without writing the main function. See the below code,



One comment

  1. The C pre-processor seems nice at first but later you realize it causes more problems then it solves. Avoid it except in the simplest cases. Token pasting can create nightmares when debugging and for context-sensitive IDEs.

    To paraphrase an old joke: “You have a problem. So you use the C pre-processor. Now you have two problems.”

Leave a Reply