#include <stdio.h>
#define Type int
int main()
{
Type x=3;
printf("%d",x);
return 0;
}
The code is simple and works fine. My question is, if I change #define Type int to #define Type float so , I have to change %d to %f as well. Is there any way to have a generic specifier, that would work for all int, float, char, string etc... So that, if I change #define Type int then I don't have to change the format specifiers within printf() function?
This is what I suggest:
There is no way to make
printf()auto-detect types in C. In C++, you can use the overloaded<<operator, and that does figure out the types automatically, but C has nothing like it.But you can
#definea format as well as a type, and if you put multiple string literals next to each other the C compiler will auto-merge them into a single string constant.P.S. Instead of using
#definefor the type, you should probably usetypedeflike so:This means that in the debugger, you can see that your variable
xis of typeTYPE, while with the#defineyou would see it as typeint.And in a perfect world you would declare the format string like so:
But we do not live in a perfect world. If you do the above declaration for
TYPE_FORMAT, the compiler is probably not smart enough to merge the string in with other string literals. (I tried it with GCC, and as I expected I got an error message.) So for theTYPE_FORMATyou absolutely should use the #define.Summary: use the
typedeffor the type but use the#definefor the format.