Is there a way to use the _Generic
keyword multiple times in the same expression to create a single string literal?
What I am looking for is a way to for example generate a single format string to pass to printf
, with all the conversion specifiers adapted to the proper types.
When writing this answer I ended up with a rather ugly work-around:
#include <stdio.h>
typedef struct {
int a;
char b;
long c;
} ABC;
// printf conversion specifiers:
#define CS(x) \
_Generic((x), \
int: "%d", \
char: "%c", \
long: "%ld")
int main (void)
{
ABC abc = {1, 'a', 2};
printf(CS(abc.a), abc.a); printf(" ");
printf(CS(abc.b), abc.b); printf(" ");
printf(CS(abc.c), abc.c); printf(" ");
return 0;
}
6 printf
calls instead of 1, hardly ideal.
The problem is that I can't find a way to combine _Generic
and string literal concatenation by the pre-processor, like this:
printf(CS(abc.a) " ", abc.a); // doesnt work
printf(CS(abc.a) CS(abc.b), abc.a, abc.b); // doesnt work either
Because apparently generic macros don't count as string literals in the pre-processor, so string literal concatenation isn't possible. I toyed around with "stringification" macros but no luck there.