Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining C++ preprocessor macro with quotation marks [duplicate]

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?

like image 875
guskenny83 Avatar asked Mar 06 '26 15:03

guskenny83


1 Answers

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);
like image 63
Sid S Avatar answered Mar 08 '26 05:03

Sid S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!