Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using macros in printf with a number sign

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.

like image 699
Spellbinder2050 Avatar asked Aug 31 '14 01:08

Spellbinder2050


1 Answers

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.

like image 85
jxh Avatar answered Sep 21 '22 23:09

jxh