Question on macro substitution

M

main()

Hi all,
I have the following code ,

#include <stdio.h>

#define f(a,b) a##b
#define g(a) #a

int main(void)
{
printf("%s\n",g(f(10,20)));
return 0;
}

Output that i got is
f(10,20)
But i expected
1020

My assumption was
1) first f(10,20) is replaced by 1020 , because of macro f(a,b)
concantenates its arguments
2) then g(a) macro replaces 1020 by a string literal "1020"
3) the output should be 1020

But why is f(10,20) not getting substituted.
I'm sure i'm missing something here.
Can someone explain me this program ?


Thanks for your time,
Yugi.
 
M

main()

main() said:
Hi all,
I have the following code ,

#include <stdio.h>

#define f(a,b) a##b
#define g(a) #a

int main(void)
{
printf("%s\n",g(f(10,20)));
return 0;
}

Output that i got is
f(10,20)
But i expected
1020

My assumption was
1) first f(10,20) is replaced by 1020 , because of macro f(a,b)
concantenates its arguments
2) then g(a) macro replaces 1020 by a string literal "1020"
3) the output should be 1020

But why is f(10,20) not getting substituted.
I'm sure i'm missing something here.
Can someone explain me this program ?


Thanks for your time,
Yugi.

I came across one more piece of code that is even more confusing..

#include <stdio.h>

#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)

int main(void)
{
printf("%s\n",h(f(1,2)));
printf("%s\n",g(f(1,2)));
return 0;
}

output is
12
f(1,2)

I'm totally lost.
I searched in this newsgroup. It has been answered before. But i
couldn't understand it.
Please can someone explain what exactly is happening here ?
 
K

Krishanu Debnath

main() said:
Hi all,
I have the following code ,

#include <stdio.h>

#define f(a,b) a##b
#define g(a) #a

int main(void)
{
printf("%s\n",g(f(10,20)));
return 0;
}

Output that i got is
f(10,20)
But i expected
1020

My assumption was
1) first f(10,20) is replaced by 1020 , because of macro f(a,b)
concantenates its arguments
2) then g(a) macro replaces 1020 by a string literal "1020"
3) the output should be 1020

But why is f(10,20) not getting substituted.
I'm sure i'm missing something here.
Can someone explain me this program ?


Thanks for your time,
Yugi.

This is a FAQ. Read Question 11.17 from http://c-faq.com/index.html

Krishanu
 

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

No members online now.

Forum statistics

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

Latest Threads

Top