Behavior of the ## Operator on a Nested Call

I read a book in the C programming language, where I found:

#define cat(x,y) x##y
#define xcat(x,y) cat(x,y)

the call cat(cat(1,2),3)causes an error, while the call xcat(xcat(1,2),3)causes the expected result 123.

How do both work differently?

+4
source share
1 answer

Macros whose replacement lists are dependent on ##cannot usually be called in a nested manner.
cat(cat(1,2),3)does not expand in the usual way, while cat(1,2)giving 12, and then cat(12, 3)giving 123.
Macro options that precede or follow ##in the notes list will not be expanded during substitution.

6.10.3.1 Substitution of the argument

1 , - , . , # ## ## (. ), , , , . , , ; .

cat(cat(1,2),3) cat(1,2)3, , cat(1,2)3 .

#define xcat(x,y) cat(x,y)  

xcat(xcat(1,2),3) . xcat, xcat(1,2); , xcat ##.

xcat(xcat(1,2),3) ==> cat(12, 3) ==> 12##3 ==> 123
+5

Source: https://habr.com/ru/post/1545475/


All Articles