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?
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With