我试图在另一个常量定义中使用常量定义,如下所示:
#define ADDRESS 5002
#define FIND "foundaddress ADDRESS"
但是当我想要将常量FIND设为findaddress 5002时,这包括FIND常量中的ADDRESS。
有没有办法做到这一点?
答案 0 :(得分:2)
如果您不介意将ADDRESS更改为字符串,则可以使用预处理器连接
#define ADDRESS "5002" /* rather than 5002 without quotes */
#define FIND "foundaddress " ADDRESS
编译器会将第二行视为
#define FIND "foundaddress 5002"
答案 1 :(得分:2)
您需要使用预处理程序字符串化运算符将您的值转换为字符串,然后像其他人所说的那样连接它们。
#define ADDRESS_TO_STRING(x) #x
#define ADDRESS 5002
#define FIND "foundaddress " ADDRESS_TO_STRING(ADDRESS)
如果这给你“foundaddress ADDRESS”,那就意味着你还需要一层:
#define ADDRESS_TO_STRING_(x) #x
#define ADDRESS_TO_STRING(x) ADDRESS_TO_STRING_(x)
#define ADDRESS 5002
#define FIND "foundaddress " ADDRESS_TO_STRING(ADDRESS)
答案 2 :(得分:1)
是
#define ADDRESS "5002"
#define FIND "foundaddress " ADDRESS
答案 3 :(得分:0)
来自C/C++ Macro string concatenation
/*
* Turn A into a string literal without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define STRINGIZE_NX(A) #A
/*
* Turn A into a string literal after macro-expanding it.
*/
#define STRINGIZE(A) STRINGIZE_NX(A)
然后
#define FIND ("foundaddress " STRINGIZE(ADDRESS))
生成(“foundaddress”“5002”),由于C的字符串文字串联,它应该可以在任何需要字符串文字的地方使用。