Arithmetic with the preprocessor

2 posts / 0 new
Last post
OldFart
OldFart's picture
Offline
Last seen: 1 day 1 hour ago
Joined: 2010-11-30 14:09
Arithmetic with the preprocessor

Hi,

I would like to do some simple math with the proprocessor, but it seems not to be possible.

  1. #define SOMECOUNTER 0
  2.  
  3.  
  4. /*Step 1: */
  5.  
  6. #ifdef Condition_1
  7. # ifdef SOMECOUNTER
  8. # define TEMPCOUNTER SOMECOUNTER + 1
  9. # undef SOMECOUNTER
  10. # define SOMECOUNTER TEMPCOUNTER
  11. # undef TEMPCOUNTER
  12. # endif
  13. #endif
  14.  
  15.  
  16. /*Step 2: */
  17.  
  18.  
  19. #ifdef Condition_2
  20. # ifdef SOMECOUNTER
  21. # define TEMPCOUNTER SOMECOUNTER + 1
  22. # undef SOMECOUNTER
  23. # define SOMECOUNTER TEMPCOUNTER
  24. # undef TEMPCOUNTER
  25. # endif
  26. #endif
  27.  
  28.  
  29. /*Step 3: */
  30.  
  31.  
  32. #ifdef Condition_3
  33. # ifdef SOMECOUNTER
  34. # define TEMPCOUNTER SOMECOUNTER + 1
  35. # undef SOMECOUNTER
  36. # define SOMECOUNTER TEMPCOUNTER
  37. # undef TEMPCOUNTER
  38. # endif
  39. #endif

I would like it to end up with a line in this vein:0 + 1 + 1 +....+1 as a value for the number of elements of an array. However, the compiler keeps telling me that "TEMPCOUNTER" is not defined, right after I defined it.

Can someone shed a bit of light on my dim wits?

OldFart

thomas
thomas's picture
Offline
Last seen: 2 hours 30 min ago
Joined: 2011-05-16 14:23
Re: Arithmetic with the preprocessor

Looks rather complicated to me.

Why not like this:

  1. #ifdef condition1
  2. # define counter1 1
  3. #else
  4. # define counter1 0
  5. #endif
  6.  
  7. #ifdef condition2
  8. # define counter2 1
  9. #else
  10. # define counter2 0
  11. #endif
  12.  
  13. #ifdef condition3
  14. # define counter3 1
  15. #else
  16. # define counter3 0
  17. #endif
  18.  
  19. #define somecounter (counter1 + counter2 + counter3)

In the best case you could even use condition_x as a 0/1 value and do

  1. #define somecounter (condition_1 + condition_2 + condition_3)
Log in or register to post comments