Programmatically determining variable type

Started by Cnoob, April 16, 2015, 04:39:30 PM

Previous topic - Next topic

Cnoob

Hi

This might be a crazy question, but how does one determine a variable type programmatically?
Is it even possible?

Reason I'm asking is that I want to implement some rudimentary debug printing statements using a macro and fprintf
and instead of having to change the %Format depending on variable type, I could do it programmatically then the proper %Format option would be inserted.

Snowman

The C11 standard supports "type generic expressions" via the _Generic keyword.
Example from Pelles C Help (which looks very similar to the Wikipedia example):

#define cbrt(X) _Generic((X), \
  long double: cbrtl, \
  default: cbrt, \
  float: cbrtf \
  )(X)


There's also the __typeof__ extension which gives you the type of its argument.

#define SWAP(a, b)  if (true) { \
    __typeof__(a) tmp = (a);    \
    (a) = (b);                  \
    (b) = tmp;                  \
} else (void)0


To be honest I think you're using the wrong programming language for this.