C中常量定义内的常量定义

时间:2013-04-18 19:06:52

标签: c constants

我试图在另一个常量定义中使用常量定义,如下所示:

#define ADDRESS 5002
#define FIND "foundaddress ADDRESS"

但是当我想要将常量FIND设为findaddress 5002时,这包括FIND常量中的ADDRESS。

有没有办法做到这一点?

4 个答案:

答案 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的字符串文字串联,它应该可以在任何需要字符串文字的地方使用。