Using macros inside a printf string in C?

Given 3 doubles x, y and z, I make a lot of such printf calls:

printf("[%+-8.3lf, %+-8.3lf, %+-8.3lf]\n", x, y, z);

I then would like to have a macro of some sort to write something like this:

#define FORMAT(x,y) "+-x.ylf"

printf("[%FORMAT(8,3), %FORMAT(8,3), %FORMAT(8,3)]\n", a->x, a->y, a->z);

But of course, the compiler sees %F as a special string and doesn’t get my macro inside the string.
Is there a way to achieve what I want ?

>Solution :

Your "something like this" code is close — but you need to use string concatenation (of adjacent string literals) and the # operator to ‘stringize’ macro arguments:

#define FORMAT(x,y) "%+-" #x "." #y "lf"

printf("[" FORMAT(8,3) ", " FORMAT(8,3) ", " FORMAT(8,3) "]\n",
       a->x, a->y, a->z);

This is similar to using the macros from <inttypes.h> for printing types such as int64_t, except with those, you have to provide the % symbol (and any flags):

uint64_t x = 0x43218765CBA9;
printf("x = 0x%.12" PRIX64 "\n", x);

Leave a Reply