Why Stringification is not working as expected

I have a C code that contains a strip as shown below.

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

Now xstr (foo) correctly evaluates to "4".

But str (foo) evaluates to "foo". But I thought it should be rated as "4". Can someone explain to me how it is rated as "foo".

+4
source share
1 answer

Due to the macro distribution rules in C. Using the str(s)one you defined is fooimmediately placed as #foo, rather than evaluates, the value foo. When you complete it with help xstr, it provides an opportunity to actually evaluate foobefore applying the structure.

The process looks something like this:

str(foo)->#foo->"foo"
xstr(foo)->str(4)->#4->"4"
+3

Source: https://habr.com/ru/post/1534734/


All Articles