This is what I suggest:
#include <stdio.h>
#define TYPE int
#define TYPE_FORMAT "%d"
int main()
{
TYPE x=3;
printf("Value of x is: " TYPE_FORMAT "\n", x);
return 0;
}
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 #define
a 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 #define
for the type, you should probably use typedef
like so:
typedef int TYPE;
This means that in the debugger, you can see that your variable x
is of type TYPE
, while with the #define
you would see it as type int
.
And in a perfect world you would declare the format string like so:
static char const * const TYPE_FORMAT = "%d";
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 the TYPE_FORMAT
you absolutely should use the #define.
Summary: use the typedef
for the type but use the #define
for the format.