2021年3月3日星期三

Using _Generic for printf formatting

I find myself often entering in the wrong formatting type, and not remembering when to do f or Lf or lf, etc. Is there a way to do something like the following with the help of the _Generic keyword?

#define TYPE(X)   _Generic((X), float: "float", double: "double", long double: "long_double")  #define FORMAT(X) _Generic((X), float: "%f", double: "%f", long double: "%Lf")    printf("%s if of type %s\n", FORMAT(10.), 10., TYPE(10.));  

Basically, I want it to print:

10.000000 is of type double

Is there a way to do that?

I suppose one shorthand option would be doing something like:

#define TYPE(X)     _Generic((X), float: "float", double: "double", long double: "long_double")  #define STRINGIZE(X)   #X  printf("%s if of type %s\n", STRINGIZE(10.), TYPE(10.));  
  1. if of type double
https://stackoverflow.com/questions/66467106/using-generic-for-printf-formatting March 04, 2021 at 08:59AM

没有评论:

发表评论