Reputation: 449
I wanna print variable value without specifying its type.
In c, I can do
int main(int argc, char **argv) {
int i = 1;
float f = 0.1;
char s[] = "s";
printf("%i\n", i);
printf("%f\n", f);
printf("%s", s);
return 0;
}
but I expect:
int main(int argc, char **argv) {
int i = 1;
float f = 0.1;
char s[] = "s";
printf("%any_type\n", i);
printf("%any_type\n", f);
printf("%any_type", s);
return 0;
}
question: is there %any_type
in C?
Upvotes: 12
Views: 8140
Reputation: 4106
In C11
you can write a generic function to print any type and keep adding your custom type to that function.
#define print_any(X) _Generic((X), int: print_int, \
default: print_unknown, \
float: print_float)(X)
int print_int(int i)
{
return printf("%d\n", i);
}
int print_float(float f)
{
return printf("%f\n", f);
}
int print_unknown(...)
{
return printf("ERROR: Unknown type\n");
}
You can also automate the function generation as shown below.
#define GEN_PRINT(TYPE, SPECIFIER_STR) int print_##TYPE(TYPE x) { return printf(SPECIFIER_STR "\n", x);}
GEN_PRINT(int, "%d");
GEN_PRINT(char, "%c");
GEN_PRINT(float, "%f");
Usage will be:
int main(int argc, char **argv) {
int i = 1;
float f = 0.1;
char s[] = "s";
print_any(i);
print_any(f);
print_any(s);
return 0;
}
Upvotes: 17
Reputation: 141658
No, you have to give the correct format specifier.
In C11 you can automate the computation of the correct format specifier by using a _Generic
combined with a macro. However, you have to repeat the name of the variable (once to compute the specifier, and once to give the variable as argument).
For more details read this link.
Upvotes: 11
Reputation: 181077
No, printf
is a so called variadic function, which means it can take any number/type of parameters.
The problem (well, one of them) with variadic functions in classic C is that the parameters are not type safe, that is - the called function has no idea of the type of the parameters.
That's the reason the variables are typed using the format string to begin with, printf has no idea whether a passed value is a pointer, an integer or some other type, and need to look at the format string to figure out in what format to display the value.
That sadly also opens up the possibility of bugs, if the format string is wrong, for example saying that a value is a pointer to something when it's really an integer, the program may crash (or more specifically, cause undefined behaviour) from trying to access a non pointer value as a pointer.
Upvotes: 6
Reputation: 163
There is no such kind of things. We have to tell at which format we are going to print that value.
Upvotes: 1