Monday, July 13, 2015

Token-Pasting Operator (##) does not concat String as I expect




Let's study below example


#include
using std::cout;
using std::endl;


#define STRINGIFY2( x) #x
#define STRINGIFY(x) STRINGIFY2(x)

#define A1 a2
#define B1 b2

#define concat2(x, y, z) x ## y z
#define concat(x,y, z) concat2(x,y, z)
int main()
{
    cout << STRINGIFY(concat2(A1, B1, A1)) << endl;
    cout << STRINGIFY(concat(A1, B1, A1)) << endl;
    
}

The output is
A1B1 a2
a2b2 a2

According to MSDN, "If a formal parameter in a macro definition is preceded or followed by the token-pasting operator, the formal parameter is immediately replaced by the unexpanded actual argument. Macro expansion is not performed on the argument prior to replacement". Thus, in the function concat2, x and y are not expanded while z is expanded. Therefore, the first line output is "A1B1 a2. Note that the space between x and y is removed. On the other hand, the function concat calls concat2 and 3 arguments, x, y, and z are computed first and send to concat2. Therefore, the output is "a2b2 a2".


No comments:

Post a Comment