NO

Author Topic: Programmatically determining variable type  (Read 2397 times)

Cnoob

  • Guest
Programmatically determining variable type
« 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.

Snowman

  • Guest
Re: Programmatically determining variable type
« Reply #1 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):

Code: [Select]
#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.

Code: [Select]
#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.