1

I'm currently reading "The C puzzle book" and I found a #define that I would like to understand how it works.

#define PRINT(int) printf(#int " = %d\n", int)

I've never seen something like #int before so I wrote a small program to try the above

#include <stdio.h>
#define PRINT(int) printf(#int " = %d\n", int)
int main()
{
    PRINT(10);
}

Result: 10 = 10

How does the preprocessor interpret #int in this case and where can I read more about this?

Thanks.

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65
Ludwwwig
  • 129
  • 1
  • 6
  • Using `#` inside C macros is called "*Stringification*" and you can read more about it here: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification – alk Mar 29 '15 at 13:17

1 Answers1

5

# stringizing operator expands the name to a quoted string, so here:

printf(#int " = %d\n", int)

to

printf("10" " = %d\n", 10);

which is equivalent to:

printf("10 = %d\n", 10);

In the example the int parameter name in the macro definition is a little bit confusing and should be replaced by something better.

ouah
  • 142,963
  • 15
  • 272
  • 331