I am trying to understand what is the flow of replacement of same2, same1 and concatenate in:
#include<stdio.h>
#define concatenate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
main()
{
printf("%s\n",same2(concatenate(1,2)));
printf("%s\n",same1(concatenate(1,2)));
}
I have tried to understand this from many places but I am not able to get it. Can somebody please explain it more clearly?
With
#define concatenate(a,b) a##b
#define same1(a) #a
#define same2(a) same1(a)
when you have same2(concatenate(1,2)), the argument of same2 is expanded before passing it to same1, so there, concatenate(1,2) is replaced by its result, 12 that then is stringified by same1 to produce "12".
With same1, no expansion of the macro argument occurs, since it's preceded by the stringification token #:
After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a
#or##preprocessing token or followed by a##preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.
(section 6.10.3.1 (1) in n1570)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With