Is there a common conversion specifier for printf?

I want to print the value of a variable 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?

+6
source share
4 answers

In C11 you can write a generic function for printing any type and continue to add your custom type to this 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); } float print_float(float f) { return printf("%f\n", f); } float print_unknown(...) { return printf("ERROR: Unknown type\n"); } 

You can also automate the generation of functions, 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; } 
+11
source

No, you need to specify the correct format specifier.

In C11, you can automate the calculation of the correct format specifier using _Generic in combination with a macro. However, you need to repeat the variable name (once to calculate the qualifier and once to specify the variable as an argument).

Read this link for more details.

+9
source

No, printf is a so-called variational function , which means that it can accept any number / type parameters.

The problem (well, one of them) with variational functions in classical C is that the parameters are not safe types, that is, the called function has no idea about the type of parameters.

That is the reason why variables are typed using a format string, first, printf has no idea whether the passed value is a pointer, integer, or some other type, and you need to look at the format string to find out what the format is for displaying the value .

This, unfortunately, also opens up the possibility of errors if the format string is incorrect, for example, saying that the value is a pointer to something, when it really is an integer, the program may crash (or, more specifically, cause undefined behavior) from attempts to access the value of a non-pointer as a pointer.

+4
source

There are no such things. We must indicate in which format we will print this value.

+1
source

Source: https://habr.com/ru/post/977694/


All Articles