4

I have C code that contains strinigication as below.

#define xstr(s) str(s)
#define str(s) #s
#define foo 4

Now xstr (foo) is evaluating as "4" correctly.

But str(foo) is getting evaluated as "foo". But I thought it should be evaluated as "4". Can any one please explain me how it is evaluated as "foo".

kadina
  • 5,042
  • 4
  • 42
  • 83
  • possible duplicate of [How to make a char string from a C macro's value?](http://stackoverflow.com/questions/195975/how-to-make-a-char-string-from-a-c-macros-value) – Jonathan Leffler Apr 03 '14 at 00:06
  • The correct reason : The problem is that when you have a macro replacement, the preprocessor will only expand the macros recursively if neither the stringizing operator # nor the token-pasting operator ## are applied to it. – kadina Apr 03 '14 at 00:48

1 Answers1

3

Because of macro expansion rules in C. Using the str(s) you defined the foo immediately gets placed as #foo rather than evaluating the value of foo. When you wrap it with xstr it gives it a chance to actually evaluate foo before applying stringification.

The process looks something like this

str(foo)->#foo->"foo"
xstr(foo)->str(4)->#4->"4"
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
  • I got one correct explanation (shamelessly copied from one of the stack overflow questions): The problem is that when you have a macro replacement, the preprocessor will only expand the macros recursively if neither the stringizing operator # nor the token-pasting operator ## are applied to it. – kadina Apr 03 '14 at 00:47
  • Yeah. I understood your example. I shouldn't have told "correct" in my comment. – kadina Apr 03 '14 at 00:55