Home >Backend Development >C++ >Can C/C Macros Directly Concatenate Strings Without Helper Functions?
Concatenating Strings Using Macros in C/C
In C/C , macros can be employed to concatenate strings. A common question arises: is it possible to directly concatenate strings defined as macros, without resorting to intermediate macro functions?
Consider the following example:
#define STR1 "s" #define STR2 "1" #define STR3 STR1 ## STR2
The goal is to concatenate STR1 and STR2 to obtain "s1" as the value of STR3. Using another macro function to pass arguments is an option, but is there a simpler method?
Direct Concatenation
Indeed, there is a straightforward way to concatenate strings directly using macros:
#define STR3 STR1 STR2
This definition results in the following expansion:
#define STR3 "s" "1"
In C, concatenating strings by separating them with a space ("s" "1") is equivalent to having a single string ("s1"). Therefore, this approach effectively achieves the desired string concatenation.
The above is the detailed content of Can C/C Macros Directly Concatenate Strings Without Helper Functions?. For more information, please follow other related articles on the PHP Chinese website!