If I'm defining a generic macro, using __typeof__/typeof, is there any way to also pick a printf conversion specifier, in a generic way ?
what I mean is, for e.g:
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
DEBUG(( "%" __PRI_TYPE_PREFIX(a) > "%" __PRI_TYPE_PREFIX(b) "?", _a, _b)) \ <-- hypothetical
_a > _b ? _a : _b; })
is possible ?
You can use C11's _Generic capability to do this, e.g.
#define printf_dec_format(x) _Generic((x), \
char: "%c", \
signed char: "%hhd", \
unsigned char: "%hhu", \
signed short: "%hd", \
unsigned short: "%hu", \
signed int: "%d", \
unsigned int: "%u", \
long int: "%ld", \
unsigned long int: "%lu", \
long long int: "%lld", \
unsigned long long int: "%llu", \
float: "%f", \
double: "%f", \
long double: "%Lf", \
char *: "%s", \
void *: "%p")
#define print(x) printf(printf_dec_format(x), x)
(example taken from: Rob's Programming Blog)
#include <stdio.h>
#define FMT(_pre_, x, _post_) _Generic((x), \
char: _pre_ "%c" _post_, \
int: _pre_ "%d" _post_, \
long: _pre_ "%ld" _post_)
int main()
{
int x = 42;
long y = 432144312432321;
printf(FMT("foo: ", x, "\n"), x);
printf(FMT("bar: ", y, "\n"), y);
return 0;
}
The pre and post stuff is a little ugly, but I didn't find a better way yet. We cannot rely on string concatenation in the C preprocessor, because _Generic is evaluated by the compiler, too late.
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