Print a #define macro using std::cout

883 views Asked by At

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?

2

There are 2 answers

0
user12002570 On BEST ANSWER

"_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 below

//-------------vvvvvv--->double quotes added here
#define _TEST_ "test" 
#include <iostream>

int main()
{
//-------------------vvvvvv---------------> not withing quotes
        std::cout << _TEST_ << std::endl;
}

The output of the above modified program is:

test

Demo

Explanation

In the modified program, the macro _TEST_ stands for the string literal "test". And thus when we use that macro in the statement std::cout << _TEST_ << std::endl;, it will be replaced by the string literal, producing the expected output.

0
Silvio Mayolo 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.