Pelles C forum

C language => Beginner questions => Topic started by: Cnoob on April 16, 2015, 04:39:30 PM

Title: Programmatically determining variable type
Post by: Cnoob on April 16, 2015, 04:39:30 PM
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.
Title: Re: Programmatically determining variable type
Post by: Snowman on April 16, 2015, 05:58:39 PM
The C11 standard supports "type generic expressions" via the _Generic keyword.
Example from Pelles C Help (which looks very similar to the Wikipedia example (https://en.wikipedia.org/wiki/C11_%28C_standard_revision%29)):

#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.