There is such a working code:

#include <stdio.h> #define T 50 #define str(s) strk(s) #define strk(s) #s int main () { puts(str(T)); } 

We know that puts on the prototype cannot output a number, only strings. I did not understand what role these two lines play for outputting a number through a substitution (in our case for T, instead of which an integer will be substituted) from puts:

 #define str(s) strk(s) #define strk(s) #s 

And why do we substitute the function str(s) this function strk(s) with an arbitrary name (instead of str(s) and strk(s) you can write anything and the program will still work without errors)? Finally, what does #s mean in this example?

2 answers 2

This is such a tricky way to force C to treat 50 not as a number (and lead to the type int ), but as the string "50" (and turn it into a sequence of 0x30 0x35 0x00 bytes).

This is done just with a macro with a grid:

 #define strk(s) #s 

The lattice serves as an indication - “treat the whole swindler that fell into s as a string”. Make sure with the help of ideone .

And this macro:

 #define str(s) strk(s) 

It is needed so that the first substitution #define T 50 opens up and is replaced by 50.

If you immediately make strk(T) , the program will turn T into a string and type "T".

This property can be used to generate debug output:

 #define PRINT(A) printf(#A " = %d\n", A); 

    In addition. Let's look at this:

     #define T 50 #define str(s) #s int main() { puts( str(T) ); return 0; } 

    Run through the preprocessor and get:

     int main() { puts( "T" ); return 0; } 

    That is, in this version, the macro str() will turn into the string not the value of the argument, but its name :) An additional run through another macro is needed because the value will fall into it (in our case, 50 ).