I am wondering if it's possible to use a C pre-processing define to change a string format specifier. I've tried writing the following, but seem to get a compiler error. It's simply trying to replace the existing format specifiers with the correct one.
#include <stdio.h>
//This is the problem line....
#define %d %llu
int main(int argc, char** argv){
unsigned long long int myInt = 0;
printf("myInt start value: %d", myInt++);
printf("myInt value=%d (that got incremented)", myInt++);
printf("myInt value: %d; wow, another post-increment", myInt++);
printf("myInt final value %d", myInt);
return 0;
}
I get the following compiler error:
error: expected an identifier
#define %d %llu
^
Why is this syntax not acceptable? Is it even possible to accomplish?
What you want to do is not possible.
Macros are not replaced within string literals and the rules for valid identifier names also apply for macro names.
What you could do is something like this:
#if xyz
#define FMT "%d"
#else
#define FMT "%lli"
#endif
....
printf("myInt start value: " FMT "\n", myInt++);
BTW:
Normally you should not need this. For the native types int
, long
etc. the format specifiers should be usable as normal.
For types with fixed size (e.g. int64_t
etc.) there are already macros defined in inttypes.h