When can I pass variable's value to a macro for stringifying?
For example the code taken from this post works with a constant-defined macro.
#define MAX_STRING_LENGTH 20 #define STRINGIFY(x) STRINGIFY2(x) #define STRINGIFY2(x) #x { ... char word[MAX_STRING_LENGTH+1]; scanf("%" STRINGIFY(MAX_STRING_LENGTH) "s", word); ... } However I cannot use it with a variable such as:
{ ... int val = 20; char word[MAX_STRING_LENGTH+1]; scanf("%" STRINGIFY(val) "s", word); ... } since the compilation is successful with this warning:
warning: invalid conversion specifier 'v' [-Wformat-invalid-specifier] scanf("%" STRINGIFY(var) "s", word); ~~~^~~~~~~~~~~~~ test2.c:4:22: note: expanded from macro 'STRINGIFY' #define STRINGIFY(x) STRINGIFY2(x) ^ test2.c:5:23: note: expanded from macro 'STRINGIFY2' #define STRINGIFY2(x) #x ^ <scratch space>:466:2: note: expanded from here "var" ^ 1 warning generated but the run of the code does not wait for any input.
On the contrary in this other post it was possible to pass a variable to this macro:
#define PRINT(int) printf(#int "%d\n",int) ... int var =8; PRINT(var); What is the difference between the two cases? How can I modify the first one so that it accepts also variables?
I tried using %d inside the macro but I was not successful.