0

I'm trying to use a constant definition in another constant definition like so:

#define ADDRESS 5002
#define FIND "foundaddress ADDRESS"

But this includes ADDRESS in the FIND constant when I want the constant FIND to be foundaddress 5002.

Is there any way to do this?

Delos Chang
  • 1,823
  • 3
  • 27
  • 47

4 Answers4

2

If you don't mind changeing ADDRESS to a string, you can use the preprocessor concatenation

#define ADDRESS "5002" /* rather than 5002 without quotes */
#define FIND "foundaddress " ADDRESS

The compiler will see that 2nd line as

#define FIND "foundaddress 5002"
pmg
  • 106,608
  • 13
  • 126
  • 198
2

You need to use the preprocessor stringification operator to make your value into a string, then concatenate them like others have said.

#define ADDRESS_TO_STRING(x) #x
#define ADDRESS 5002
#define FIND "foundaddress " ADDRESS_TO_STRING(ADDRESS)

And if that gives you "foundaddress ADDRESS", it means you need one more layer:

#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)
Medinoc
  • 6,577
  • 20
  • 42
1

Yes.

#define ADDRESS "5002"
#define FIND "foundaddress " ADDRESS
Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
0

From 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)

Then

#define FIND ("foundaddress " STRINGIZE(ADDRESS))

produces ("foundaddress " "5002") which should be usable wherever you need a string literal, due to C's string literal concatenation.

Community
  • 1
  • 1
Jim Balter
  • 16,163
  • 3
  • 43
  • 66