I have found two different things in two well known books in c,
first one is
“Formal parameters are not replaced in quoted string in macro expansion” – by K&R c language page 76
second one is a code,
#define PRINT(var,format) printf("variable is %format\n",var)
PRINT(x_var,f);
later macro invocation would be expanded as
printf("x_var is %f\n",x_var);
- this is by programming in ansi c – E. balagurusamy at page 448.
Surely two citations are contradictory one with another. as far I know first one is true and my compiler giving me result so. But second book is also well known and popular. I want to know if there was such things in previous versions of c or the second citation is a false one.
The second book is wrong: it is easy to check that the macro will not be expanded like that. However, you can get the effect that they describe by stringizing tokens using the
#preprocessor operator:Now you can print your variable as follows:
Here is a link to a working sample on ideone.
Note the addition of the double quotes before and after the ‘#format’, and the ‘#’ before ‘var’ and ‘format’. The ‘#’ operator causes the value of the variable to be made into a quoted string — with double quotes of its own. This makes the replaced strings be four quoted strings in a row, that the C compiler recognizes as a request to concatenate into one string. Thus the strings: “xyz”, ” is %”, “d” and “\n” are concatenated into: “xyz is %d\n”
(Note this example is different from the example in the original question in that the orignal example had “variable is…” where the answer replaced ‘variable’ with an instance of the ‘var’ macro argument)