I know that:
#define foo 4 #define str(s) #s with str(foo) writes out: "foo", because stringify is executed first of text expansion, but this:
#define xstr(s) str(s) #define str(s) #s #define foo 4 with xstr(foo) writes out: "4".
Why? What are the steps involved in the process?
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.
parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string. Follow this answer to receive notifications.
The relevant steps of macro expansion are (per C 2011 [n1570] 6.10.3.1 and C++ 1998 16.3.1):
# or ##.Thus, with xstr(foo), we have:
str(s), contains no # or ##, so nothing happens.foo is replaced with 4, so it is as if xstr(4) had been used.str(s), the parameter s is replaced with 4, producing str(4).str(4) is rescanned. (The resulting steps produce ”4”.)Note that the problem with str(foo) is that step 2, which would replace foo with 4, comes after step 1, which changes the argument to a string. In step 1, foo is still foo; it has not been replaced with 4, so the result is ”foo”.
This is why a helper macro is used. It allows us to get a step 2 performed, then use another macro to perform step 1.
str(foo): Substitute str(foo) with #foo, ie "foo" xstr(foo): Substitute xstr(foo) with str(<foo-value>), ie str(4) str(4): Substitute str(4) with #4, ie "4" preprocessor evaluates macro-functions expanding macro-variables, until it is nothing to evaluate:
If you define
#define xstr(s) str(s) + 1 #define str(s) s + 1 in the following code
#define foo 4 int main() { std::cout << str(foo) << '\n' << xstr(foo) << '\n' ; } it would evaluate like
str(foo) with <foo-value> + 1, ie 4 + 1 And result is 4 + 1
xstr(foo) with str(<foo-value>) + 1, ie str(4) + 1 str(4) with <4-value> + 1, ie 4 + 1 And result is 4 + 1 + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With