0

I have a utility macro "STR" in some old C++ code that I used to create formatted strings for printing.

#define STR(__msg) ({ std::stringstream __ss; __ss << __msg; __ss.str(); })

cout << STR("Hello" << "World" << "!" << "\n");

I couldn't remember why this code works. I did some googling and didn't find anything useful so I figured I'd ask here. Any takers?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Stephan
  • 1,007
  • 7
  • 9
  • 1
    It doesn't work all the times (e.g., `STR((true)? 1 : 0);`). – 101010 Aug 28 '14 at 21:54
  • 1
    `({` `})` macro's syntax is a g++ extension. It "returns" last's instruction's value, so whole macro makes a `std::stringstream __ss`, transfers `__msg` to it, and "returns" stringizyed `__ss`'s value, and that's what you print. – GingerPlusPlus Aug 28 '14 at 21:59
  • 1
    I'd recommend you to avoid this syntax, it makes simple things complicated and compiler-dependent. – GingerPlusPlus Aug 28 '14 at 22:05
  • "statement expression" is what I needed to google for. https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html This code will only ever be used on Linux/gcc, so being compiler dependent isn't a problem. – Stephan Aug 29 '14 at 13:53

0 Answers0