Macros in C and C++ belong to the category of compiler preprocessing.
Single pound sign # operator
Single pound sign # (stringification operator) is used to convert macro parameter variable name into a string (Stringfication).
Here's an example:
#include <stdio.h>
#define PRINT_VARIABLE(x) printf(#x " = %d\n", x)
int main() {
int num = 10;
PRINT_VARIABLE(num);
return 0;
}
In the above example, #x
will convert the parameter x
received by the macro PRINT_VARIABLE into a string constant. In this example, the parameter variable name received by PRINT_VARIABLE is num, so #x
is equivalent to "num"
, which will be displayed when outputting:
num = 10
Double pound sign ## operator
Double pound sign ## (concatenator, concatenator) is used to connect two tokens (Token) together
For example:
#include <stdio.h>
#define CONCAT(x, y) x##y
int main() {
int result = CONCAT(3, 5);
printf("Result: %d\n", result);
return 0;
}
The output is:
Result: 35
Another example:
#define LINK_MULTIPLE(a,b,c,d) a##_##b##_##c##_##d
typedef struct _record_type LINK_MULTIPLE(name,company,position,salary);
When expanded, this statement is equivalent to:
typedef struct _record_type name_company_position_salary;
Notice
It should be noted that the # and ## operators can only be used in macro definitions, and their use needs to be careful to avoid unexpected behavior.
Reference: https://www.cnblogs.com/lixiaofei1987/p/3171439.html