Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic conversion specifier for printf?

Tags:

c

printf

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?

like image 845
roroco Avatar asked Nov 04 '14 05:11

roroco


2 Answers

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;
}
like image 114
Gyapti Jain Avatar answered Oct 06 '22 10:10

Gyapti Jain


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.

like image 29
M.M Avatar answered Oct 06 '22 11:10

M.M