1

I seek format_spec function. Context described below.
Is there any compile-time function like that ?

#include <stdio.h>
#define typeof(x) __typeof(x)

int main(){
  int x;         /* Plain old int variable. */
  typeof(x) y=8;   /* Same type as x. Plain old int variable. */

  //printing
  printf(format_spec(typeof(x)), y);
  /*I don't want to use:
    printf("%d", y);
  I want generic way to get format specifier for any type.*/
}
Sir
  • 337
  • 1
  • 7

1 Answers1

2

C has no generic way of formatting and provides only limited features for type introspection. For a fixed list of types, you can use _Generic:

printf(
    _Generic(x,
        int:      "%d\n",
        unsigned: "%u\n",
        long int: "%ld\n",
        char *:   "%s\n"),
    x);

However, this is cumbersome and is generally not what C was designed for. In C, you should mostly know the types you are working with and avoid issues like this.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312