3

I am trying to define a macro in C++ that puts quotes around a variable.

A simplified example of what I am trying to do is this:

#define PE(x) std::cout << "x" << std::endl;

and then when I type PE(hello) in my code, it should print hello; but instead it just prints x.

I know that if I make it:

#define PE(x) std::cout << x << std::endl;

and then type PE("hello") then it will work, but I would like to be able to be able to use it without the quotation marks.

Is this possible?

guskenny83
  • 1,321
  • 14
  • 27

1 Answers1

2

You can use the stringizing operator, #:

#define PE(x) std::cout << #x << std::endl;

I would suggest that you remove the semicolon from your macro, though. So,

#define PE(x) std::cout << #x << std::endl
...
PE(hello);
Sid S
  • 6,037
  • 2
  • 18
  • 24