user3612463 user3612463 - 8 months ago 45
C Question

Use of # in a macro

Please explain the code

#include <stdio.h>
#define A(a,b) a##b
#define B(a) #a
#define C(a) B(a)





I don't understand, how the first printf evaluates to 12?
Isn't it similar to the second, as C macro is simply a wrapper to B macro?


The confusion here comes from a simple rule.

When evaluating a macro the pre-processor first resolves the macros in the arguments passed to the macro. However, as a special case, if an argument is right of # or adjacent to ##, it doesn't resolve macros within such arguments. Such are the rules.

Your first case


The pre-processor first applies the C(a) macro, which is defined as B(a). There's no # or ## adjacent to the argument in the definition (none of them in B(a) at all), thus the pre-processor must resolve macros in the argument:


The definition of A(a,b) is a##b which evaluates into 12.

After the macros in the arguments of the C(a) macro are evaluated, the C macro becomes:


The pre-processor now resolves the C(a) macro, which according to its definition becomes


Once this is done, the pre-processor evaluates macros inside the result once again and applies the B(a) macro, so the result becomes


Your second case


Similar to the first case, the pre-processor first applies the B(a) macro. But this time, the definition of the macro is such that the argument is preceded by #. Therefore, the special rule applies and macros inside the argument are not evaluated. Therefore, the result immediately becomes:


The preprocessor goes over the result again trying to find more macros to expand, but now everything is a part of the string, and macros don't get expanded within strings. So the final result is: