Invoking a macro from a printf statement in C

I have a problem understanding the use of macro function calls from the printf () statement.

I have the code below:

#include<stdio.h> #define f(g,h) g##h main() { printf("%d",f(100,10)); } 

This code outputs "10010" as an answer.

I found out that calling a macro function simply copies by pasting a macro function code instead of a call with replaced arguments.

So, the code should look like this:

 #include<stdio.h> #define f(g,h) g##h main() { printf("%d",100##10); } 

But when I executed the above code separately with the replaced macro, I get a compilation error.

So, how does the first code give 10010 as an answer, and the second code gives a compilation error?

+6
source share
3 answers

The preprocessor concatenation operator ## is executed before the macro is replaced. It can only be used in macro bodies.

+15
source

The ## operator has a special meaning for the preprocessor, it is a paste token operator that "glues" two tokens together. So, in your case, g and h “glued” together, as a result, a new token appears - int literal 10010 .

+1
source

There are some special characters in the macro, such as ## , that change the rule "just replaces the text."

+1
source

All Articles