Kalle Rutanen wrote:
Given is a short code snippet. Executing this on VsC++2003 gives output
TEXT and Hello. Is this correct according to the standard? Why not Hello
and Hello?
#include <iostream>
using namespace std;
#define TEXT Hello
#define QUOTE(x) #x
#define QUOTE2(x) QUOTE(x)
#define DIRECT QUOTE(TEXT)
#define INDIRECT QUOTE2(TEXT)
int main()
{
cout << DIRECT << endl;
cout << INDIRECT << endl;
return 0;
}
Yes, it's correct according to the Standard. The difference is in the
[pre-]processing of a macro that expands into another macro and a macro
that expands into #x. In the former, the substitution of all macros
happens. In the latter, macros that preceded by '#' are not substituted
further. Or something like that, anyway. See clause 16.3.
DIRECT --> full substitution --> QUOTE(TEXT) --> since it expands in #x,
the 'TEXT' is not substituted --> "TEXT"
INDIRECT --> full substitution --> QUOTE2(TEXT) --> full substitution -->
QUOTE(Hello) --> since it expands into #x, the 'Hello' is not replaced -->
"Hello"
V