1

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

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!

Community
  • 1
  • 1
Gnubie
  • 2,587
  • 4
  • 25
  • 38

1 Answers1

5

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644