Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C #define based in another #define error

So my Visual studio is declaring both tag1 and tag2 as undefined, but they are cleary defined, can't i define one based on the other?

#define push                99
#define last_instruction    push

#ifdef DEBUG
    #define new_instr   (1+last_instruction) //should be 100
    #undef  last_instruction
    #define last_instruction   new_instr    //redifine to 100 if debug
#endif

I have some cases with tag2 and it says that the definition must be const, but it is constant it is 1+99, any help would be appreciated.

Thanks! BA

like image 319
mfabruno Avatar asked Mar 16 '26 18:03

mfabruno


2 Answers

First of all, you can't define the same macro twice. If you need to replace a macro, you first have to #undef it:

#define tag1    99
#ifdef DEBUG
    #define tag2   (1+tag1)
    #undef tag1
    #define tag1   tag2
#endif

But this will not solve the problem. Macros are not variables, you can't use them to store values to re-use at a later point. They are text replacement, so they sort of exist in parallel.

So the new definition #define tag1 tag2 expands to 1+tag1. But at this point, there is nothing called tag1, because we just undefined it and we are not yet done re-defining it.

Ponder this too much and you'll turn crazy :) So just forget about that whole thing, what you really want to do is this:

#define tag1_val  99
#define tag1      tag1_val

#ifdef DEBUG
    #undef tag1
    #define tag1  (tag1_val+1)
#endif
like image 186
Lundin Avatar answered Mar 18 '26 09:03

Lundin


Based on the answers provide I came up with a solution that although not perfect do best suit my case.

This implementation can be done in two forms:

Less changes in the future (only change 'last'):

#define push                   99
#define last                   push

#ifdef DEBUG
    #define new_instr          (1+last) 
    #define last_instruction   new_instr    
#else 
    #define last_instruction   last
#endif

OR

Clear Code but repeat 'push' in two places

#define push                   99

#ifdef DEBUG
    #define new_instr          (1+push) 
    #define last_instruction   new_instr    
#else 
    #define last_instruction   push
#endif

Thanks for the help.

like image 45
mfabruno Avatar answered Mar 18 '26 10:03

mfabruno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!