Stringizing

H

happy

#include<stdio.h>
#define pstr(x) printf(#x)

int main()
{
pstr("Hello");
printf("\n");
return 0;
}

I thought that pstr("Hello") will expand to printf(""Hello"") which
will give compile error.
But it prints "Hello".
How expansion is working?
 
B

Ben Bacarisse

happy said:
#include<stdio.h>
#define pstr(x) printf(#x)

int main()
{
pstr("Hello");
printf("\n");
return 0;
}

I thought that pstr("Hello") will expand to printf(""Hello"") which
will give compile error.

No, it *should* expand to printf("\"Hello\""); which is what my gcc
does.
But it prints "Hello".
How expansion is working?

That is as expected.
 
L

lawrence.jones

happy said:
#include<stdio.h>
#define pstr(x) printf(#x) [...]
I thought that pstr("Hello") will expand to printf(""Hello"") which
will give compile error.
But it prints "Hello".
How expansion is working?

Correctly. Stringizing doesn't just slap quotes around the value of the
argument, it escapes any metacharacters, too. So pstr("Hello\n")
expands to printf("\"Hello\\n\"").
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top