1

I want to do real addition (not just a replacement) of two macros and want to use their result in another macro.

for example.

#define NUM_1 1
#define NUM_2 2
#define NUM_3 3

#define ADD(X,Y)   ((X)+(Y))

#define CAT_(X,Y)   X##Y   //For two layer of indirection
#define MY(NUMBER)  CAT_(NUM_,NUMBER)

now this I want to use some thing like this

MY( ADD(NUM_1 , NUM_2 ))

or by this way

#define RESULT ((NUM_1) + (NUM_2))

MY( RESULT ) 

I'm expecting output as of MY(RESULT) or MY(ADD(NUM_1,NUM_2)) as

 NUM_3 

Is it possible to do in the preprocessing stage? If yes please guide me how I can do.

I'm getting result NUM_((1)+(2)) which is completely fine according to preprocessor output.

I have framed my problem in simple addition form. Actually, My requirement is to use a result of one complex equation which will make relation to some 1000 macros in form of like EEPROM_PAGE_10 here 10 is an output of some other equation came by an arithmetic operation on another #define macro and this I can't forward to the compiler.

Note This question is not same as Can I add numbers with the C/C++ preprocessor? because in that post we are replacing with the well-known result, for example, they have defined the macro like

#define ADD_1_AND_2 3

my requirement is different, I want to know that, Is it possible to convert ((2)+(1)) equal to 3 in preprocessing stage. so I can use 3 as NUM_3 for generating relevant output.

  • 4
    Stay away from macros looking like functions. – Ron Aug 25 '17 at 10:55
  • The compiler will likely do this addition itself. – ForceBru Aug 25 '17 at 10:56
  • You cannot do that... but you might be able to do something way better if you learn template, constexpr and modern C++ in general... but it won't be token like that so we need to know what you are trying to achieve. I don't see how the above macro could be useful if it would works like you want except maybe for code obfuscation... – Phil1970 Aug 25 '17 at 11:06
  • @Phil1970 I have modified my post to give some better clarity. please let me know if you need some more info – Bebhav Soni Aug 25 '17 at 11:21
  • No, impossible. You have to use stuff like `#define ADD_1_AND_3 3`, probably generated with a script. – HolyBlackCat Aug 25 '17 at 17:32
  • If this gets reopened, the answer is certainly **yes**: include [Order-PP](https://github.com/polytypic/order-pp) and you can more or less `#define ADD(X, Y) ORDER_PP(8add(X, Y))` then have `ADD(1, 2)` expand to `3`. – Alex Celeste Aug 26 '17 at 13:22

0 Answers0