5

I'm a bit confused about an explanation concerning macros in K&R 2nd Ed, p.90. Here is the paragraph:

Formal parameters are not replaced within quoted strings. If, however, a parameter name is preceded by a # in the replacement text, the combination will be expanded into a quoted string with the parameter replaced by the actual argument.

I'm not sure what that second sentence is saying. It goes on to explain a use for this with a "debugging print macro".

This can be combined with a string concatenation to make, for example, a debugging print macro:

#define dprint(expr) printf(#expr " = %g\n", expr);

Edit:

All the input was useful. Thank you guys.

4 Answers 4

5

If you define macro like this:

#define MAKE_STRING(X) #X

Then, you can do something like this:

puts(MAKE_STRING(a == b));

Which will expand into:

puts("a == b");

In the dprint() example, it is printing out a string form of the expression, as well as the expression value.

dprint(sin(x)/2);

Will expand into:

printf("sin(x)/2" " = %g\n", sin(x)/2);

String literal concatenation will treat the first parameter as a single string literal.

Sign up to request clarification or add additional context in comments.

Comments

3

It is just a neat feature where you can convert a macro parameter into a string literal which mainly is useful for debugging purposes. So

dprint(x + y);

is expanded by the C preprocessor to this

printf("x + y = %g\n", x + y);

Notice how the value of the parameter expr appears both inside the string literal and also in the code generated by the macro. For this to happen you need to prefix expr with # to create a string literal.

One thing worth pointing out is that adjacent string literals are combined into a single string literal, e.g. "x + y" " = %g\n" are combined into "x + y = %g\n".

Comments

2

#expr is expanded into "expr". Two string literals next to each other are automatically concatenated. We can see that invoking gcc -E for dprint(test) will give the following output:

("test" " = %g\n");

Comments

0

This site may help. It describes how stringification can be implemented.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.