I am trying to do this
#define _TEST_ test
#include <iostream>
int main()
{
std::cout << "_TEST_" << std::endl;
}
As far as my understanding, I expect this output.
test
However, the output I get is
_TEST_
Why am I doing wrong here?
On
Macro expansion in the C/C++ preprocessor only happens to tokens. Variables names, for instance, are tokens. But the inside of a string is not a token; it's a part of a larger token (namely, the string literal itself).
If you want the macro to expand to something within quotation marks, you need to use stringification.
#define xstr(x) str(x)
#define str(x) #x
#define _TEST_ test
#include <iostream>
int main()
{
std::cout << xstr(_TEST_) << std::endl;
}
You can read the above link for why we need those extra two layers of indirection (xstr and str), but the basic idea is that # itself doesn't do macro expansion, so by calling xstr, we force a macro expansion of the argument (_TEST_ into test, namely), and then separately we call str to stringify that. If we had just called str directly, it would see #_TEST_ and not perform macro expansion.
"_TEST_"is a string literal and not a macro. So no macro replacement will be done due to"_TEST_". To achieve your expected output you need to remove the surrounding double quotes and also change the macro to as shown belowThe output of the above modified program is:
Demo
Explanation
In the modified program, the macro
_TEST_stands for the string literal"test". And thus when we use that macro in the statementstd::cout << _TEST_ << std::endl;, it will be replaced by the string literal, producing the expected output.