5

Take a look at this code:

#include <iostream>
using namespace std;

#define foo bar

#define string(a) #a
#define concat(a,b) string(a ## b)
#define concat2(a,b) concat(a,b)

int main()
{
    cout << concat(foo, baz) << '\n' << concat2(foo, baz) << endl;
}

The output of this program is:

foobaz
barbaz

Why does adding an additional level of indirection change the behavior of this code?

user697683
  • 1,423
  • 13
  • 24
  • Seems like the preprocessor doesn't evaluate macros when passed as operands to the concatenation operator... – cadaniluk Nov 22 '15 at 16:00
  • duplicate of this http://stackoverflow.com/questions/2751870/how-exactly-does-the-double-stringize-trick-work ? – fghj Nov 22 '15 at 16:49
  • In addition to the duplicate, it's worth noting that there is no need to concatenate tokens in order to stringify, and trying to do so often leads you into trouble. All you need to do is work around the whitespace. See this answer: http://stackoverflow.com/a/32077478/1566221 – rici Nov 22 '15 at 16:50

0 Answers0