What is the token pasting operator and stringizing operator in C?

Token pasting operator

ANSI has introduced a well-defined token-pasting operator, ##, which can be used like this:

#define f(g,g2) g##g2



  int var12=100;





Stringizing operator

#define sum(xy) printf(#xy " = %f\n",xy);



    sum(a+b); // As good as printf("a+b = %f\n", a+b);


So what does the message “warning: macro replacement within a string literal” mean?

#define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)

TRACE(i, %d);

gets expanded as

printf("TRACE: i = %d\n", i);

In other words, macro parameters were expanded even inside string literals and character constants. Macro expansion is *not* defined in this way by K&R or by Standard C. When you do want to turn macro arguments into
strings, you can use the new # preprocessing operator, along with string literal concatenation:

#define TRACE(var, fmt) printf("TRACE: " #var " = " #fmt "\n", var)

See and try to understand this special application of the strigizing operator!

#define Str(x) #x
#define Xstr(x) Str(x)
#define OP plus

char *opname = Xstr(OP); //This code sets opname to “plus” rather than “OP”.

Here are some more examples


Define a macro DEBUG such that the following program

int main()
int x=4;
float a = 3.14;
char ch = 'A';

DEBUG(x, %d);
DEBUG(a, %f);
DEBUG(ch, %c);


DEBUG: x=4
DEBUG: y=3.140000

The macro would be

#define DEBUG(var, fmt) printf("DEBUG:" #var "=" #fmt "\n", var);


Write a macro PRINT for the following program

int main()
int x=4, y=4, z=5;
int a=1, b=2, c=3;

such that it outputs

x=4 y=4 z=5
a=1 b=2 c=3

Here is a macro that will do this

#define PRINT(v1,v2,v3) printf("\n" #v1 "=%d" #v2 "=%d" #v3 "=%d", v1, v2, v3)

5 Responses to “What is the token pasting operator and stringizing operator in C?”

  1. Shashank Says:

    well explained…

  2. kbcbcc Says:

    tell me ,wat is use of macro pasting??

  3. Enes Says:

    thanks for writing…

  4. holidays Says:


    […]What is the token pasting operator and stringizing operator in C? « TheWarrior[…]…

  5. arun kumar R Says:

    good example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: