Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessor: stringize macro and identity macro

I want to know the reason behind the output of this code. I couldn't come up with an answer.

#define f(a,b) a##b
#define g(a) #a
#define h(a) g(a)
void main()
{
   printf("%s %s",h(f(1,2)),g(f(1,2)));
}

PS: output is 12 f(1,2). I thought it was 12 12 or f(1,2) f(1,2).

like image 256
Vindhya G Avatar asked Jul 23 '12 09:07

Vindhya G


People also ask

What is difference between preprocessor and macros?

Macro: a word defined by the #define preprocessor directive that evaluates to some other expression. Preprocessor directive: a special #-keyword, recognized by the preprocessor. Show activity on this post. preprocessor modifies the source file before handing it over the compiler.

What is a preprocessor macro?

Macros allow you to write commonly used PL/I code in a way that hides implementation details and the data that is manipulated and exposes only the operations. In contrast with a generalized subroutine, macros allow generation of only the code that is needed for each individual use.

What is macro identifier in C?

Identifiers that represent statements or expressions are called macros. In this preprocessor documentation, only the term "macro" is used. When the name of a macro is recognized in the program source text, or in the arguments of certain other preprocessor commands, it's treated as a call to that macro.

Are macros removed after preprocessing?

Explanation: True, After preprocessing all the macro in the program are removed.


2 Answers

h(f(1,2))

f(1,2) is substituted for a. a is not the subject of a # or ## operator so it's expanded to 12. Now you have g(12) which expands to "12".

g(f(1,2))

f(1,2) is substituted for a. The # operator applied to a prevents macro expansion, so the result is literally "f(1,2)".

like image 197
Potatoswatter Avatar answered Oct 20 '22 18:10

Potatoswatter


Just do the replacements.

h(f(1, 2)) -> g(12) -> "12"

g(f(1,2)) -> "f(1, 2)"

You should also see here.

like image 34
md5 Avatar answered Oct 20 '22 19:10

md5