Link to home
Start Free TrialLog in
Avatar of rtsh
rtsh

asked on

Joining and expanding #defines

Fundamentally, I'd like to join two #defined constants to form a new constant, and use the value of that third constant in a subsequent operation.

For example, something like:

#define one apple
#define two pie
#define applepie 0x12345678

i=*onetwo

and i should end up with the value in location 0x12345678
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi rtsh,

you can do that in effect but not like that

int i =strlen(one);
i += strlen(two);

char * a = (char *)calloc (i+1);
strcpy (a,one);
strcat(a,two);

now you can use a as a concatenated value

Sunnycoder
rtsh,

> and i should end up with the value in location 0x12345678
that may not be necessarily possible ... you can try to write to that location but most likely you will end up getting a segfault

Sunnycoder
Avatar of rtsh
rtsh

ASKER

Sunnycoder:

Re the segfault - I'm well aware... was just an example.  

I really don't like the strcpy method - there must be a way to do this preprocessor?

I can join defines with ##, but I can't seem to force the order so that they're evaluated prior to the catenation - I'd just get onetwo, which doesn't exist...
Hi rtsh,

Using the preprocessor,you can't do that.

>but I can't seem to force the order so that they're evaluated prior to the catenation - I'd >just get onetwo, which doesn't exist

Precisely why.

#defines cannot be forced to evaluate before the substitution.
Avatar of rtsh

ASKER

I've finally found the answer - see:

http://tigcc.ticalc.org/doc/cpp.html#SEC28 which says:

"Macros that call other macros that stringify or concatenate:

If an argument is stringified or concatenated, the prescan does not occur. If you want to expand a macro, then stringify or concatenate its expansion, you can do that by causing one macro to call another macro that does the stringification or concatenation. For instance, if you have

#define AFTERX(x) X_ ## x
#define XAFTERX(x) AFTERX(x)
#define TABLESIZE 1024
#define BUFSIZE TABLESIZE

then AFTERX(BUFSIZE) expands to X_BUFSIZE, and XAFTERX(BUFSIZE) expands to X_1024. (Not to X_TABLESIZE. Prescan always does a complete expansion.) "

Avatar of rtsh

ASKER

(Can an admin close this now I've found the answer?)
ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial