Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic way to printf a variable?

Tags:

c

printf

macros

If I have a macro like

#define MYMACRO(x) printf ("%any\n", x);

is there any %any formatter which can print anything, context-dependently?

Non-standard or GNU C specific are OK.


1 Answers

Update: Rewritten to focus more on the macro aspect.

If you limit yourself to a single argument, it's doable in C11 using generics. The linked-to page has an example, the gist of which is to use generics to map the type of the argument to the proper formatting string.

I don't want to "re-print" the entire blog post, but the macro begins:

#define printf_dec_format(x) _Generic((x), \
    char: "%c", \
    signed char: "%hhd", \
    unsigned char: "%hhu", \
   /* more code deleted */

#define print(x) printf(printf_dec_format(x), x)
#define printnl(x) printf(printf_dec_format(x), x), printf("\n");
like image 102
unwind Avatar answered Oct 25 '25 11:10

unwind