简体   繁体   中英

Token concatenation in GNU C/C++ macro

I wish to write a macro to output the text of an expression and its value, eg

int a = 2;
PRINT(a + 1);

should output

a + 1 = 3

C/C++ Macro string concatenation shows the use of token concatenation. However,

#define PRINT(x) std::cout << x " = " << x << "\n"

or

#define PRINT(x) std::cout << (x) " = " << x << "\n"

gives

error: expected ';' before string constant

while

#define PRINT(x) std::cout << x##" = " << x << "\n"

gives

error: pasting "1" and "" = "" does not give a valid preprocessing token

How can I achieve my aim, please? Thanks!

Use a single # before a macro parameter to turn it into a string.

Also put parentheses around normal uses of the parameter, to prevent surprising effects of operator precedence.

#define PRINT(x) std::cout << #x " = " << (x) << "\n"
                              ^           ^ ^

You don't want token concatenation here (or in the question you link to, as the answer there describes); that's not used to combine string literals (which is done automatically), but to bodge two tokens together to make a single one, for example

#define DECLARE_TWO_VARIABLES(x) int x ## 1, x ## 2;
DECLARE_TWO_VARIABLES(stuff)

expands to

int stuff1, stuff2;

concatenating 1 and 2 onto the argument stuff to create single tokens stuff1 and stuff2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM