Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does #x inside a C macro mean?

Tags:

c

macros

For example I have a macro:

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

I kinda know what is the result. But how come #int repersent the whole thing?

I kinda forget this detail. Can anybody kindely give me a hint?

Thanks!

like image 275
Anders Lind Avatar asked Jan 16 '13 05:01

Anders Lind


2 Answers

In this context (applied to a parameter reference in a macro definition), the pound sign means to expand this parameter to the literal text of the argument that was passed to the macro.

In this case, if you call PRINT(5) the macro expansion will be printf("5" "%d\n", 5); which will print 5 5; not very useful; however if you call PRINT(5+5) the macro expansion will be printf("5+5" "%d\n", 5+5); which will print 5+5 10, a little less trivial.

This very example is explained in this tutorial on the C preprocessor (which, incidentally, is the first Google hit for c macro pound sign).

like image 198
metamatt Avatar answered Oct 22 '22 13:10

metamatt


"#" can show the name of a variable, it's better to define the macro as this:

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

and use it like this:

int i = 5;
PRINT(i);

Result shown:

i = 5
like image 19
Jack Peking Avatar answered Oct 22 '22 13:10

Jack Peking