Domanda

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?

È stato utile?

Soluzione

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)

Altri suggerimenti

Your concatinate(a,b) becomes concatinate(1,2) when 1 and 2 are passed as parameters. That in turn becomes 1##2 which translates to 12 because ## is a concatenating operator. So parameters 1 and 2 are concatenated to become 12

Same1(a) becomes simply #a, where # is stringisizing operator (See http://c-faq.com/ansi/stringize.html). So Same1(12) becomes "12" and when printed out to console

Same2(a) is the same as Same1(a), which is simply #a, which just outputs parameter a as-is; so the output of Same2(a) where parameter a is 'Concatenate(1,2)' is just a string "Concatenate(1,2)"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top