By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,905 Members | 1,283 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,905 IT Pros & Developers. It's quick & easy.

Preprocessor and standard

P: n/a
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;
}

--
http://kaba.hilvi.org
Oct 21 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Looks correct to me, I think this opens when you think it this way: the
QUOTE2 macro will substitute the TEXT with Hello, because you don't
have # in that macro.

Therefore the second macro you call will see #x being the definition of
the first, hence, Hello.

In short: looks logical and correct.. but could be wrong, what seems to
be the problem?

Oct 21 '05 #2

P: n/a
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
Oct 21 '05 #3

P: n/a
Thanks persenaama and Victor, that made it clearer.

--
http://kaba.hilvi.org
Oct 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.