Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print a #define macro using std::cout

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_TEST_

Why am I doing wrong here?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading