Home > Enterprise >  How to make this dprint macro work for all types in C?
How to make this dprint macro work for all types in C?

Time:10-08

I'm trying to improve upon a macro from the K&R C book. It is used to print an expression and its value.

#define  dprint(expr)  printf(#expr " = %g\n", expr)

However, when I use it to print an int, it prints a very low number, such as "4.023e-325" regardless of the value of the int.

If I use the %d format, the correct value is printed.

How can I alter the function to print in the correct format depending on the type of "expr"?

CodePudding user response:

You can use a type-generic macro:

#define dprint(expr) printf(#expr " = %" _Generic((expr), \
                 double: "g",  \
                 int: "d",     \
                 char *: "s",  \
                 long: "ld"    \
                 ) "\n", expr)

CodePudding user response:

If the result of the expression is a number simply cast it to double - but of course it will not be precise in some cases

#define  dprint(expr)  printf(#expr " = %g\n", (double)(expr))

int main(void)
{
    dprint(1);
    dprint(3*3);
}

https://godbolt.org/z/qdb7hcssr

  •  Tags:  
  • c
  • Related