0

I need to convert an expression to its result before applying it on a preprocessor. This is probably a simple problem, but I couldn't figure out a way to do it.

My preprocessor is like this:

#define ABCD(BITPOS) \
   if(BIT##BITPOS##_MASK & 0x01) { \
     Do something; }

And BIT0_MASK to BIT100_MASK is defined at some place. If I call ABCD(5), preprocessor converts it to BIT5_MASK and it works fine.

But, I want to call it like this: ABCD(START_VAL+2), it gives me compilation error saying BITSTART_VAL is not declared, )_MASK is not defined and whole bunch of related errors.

How can I make it work ? Appreciate your responses.

3
  • What are you actually trying to achieve? You're telling us how you're doing something without telling us what that something is. From the look of it, if we knew what you were trying to do, we could probably suggest a much better way. Commented Mar 17, 2014 at 22:29
  • 1
    IIRC it is not possible to achieve directly: the preprocessor lazily evaluates such expressions (= only if required, e.g. for a conditional inclusion). The boost PreProcessor library contains (at least) two techniques to deal with the problem: evaluated slots and INC/DEC macros. Commented Mar 17, 2014 at 22:35
  • @Emmet: Basically, this macro is a legacy code, and it does create some get/set/isSet/clrBit functions inside, and is more complicated than I put above. Basically, the if check I put above is part of isSetxxx() function. Commented Mar 18, 2014 at 14:17

2 Answers 2

2

The preprocessor macro system cannot evaluate arithmetic operators. It can only splice tokens together and substitute identifiers.

You will need to find another solution.

If you really really must do this, the folks at Boost created macros to perform some basic arithmetic, using only splicing and substitution as a basis. That is not an appropriate tool for this job, though.

Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you need an inline function rather than a macro.

inline size_t ABCD(unsigned int bitmask)
{
  if (bitmask & 0x01U)
  {
    something();
  }
}

The inline keyword will hint to the compiler that you want the code to be pasted rather than called.

1 Comment

Thanks for the reply. Forgot to mention, all of it is existing code which I cant touch, except the new call of ABCD(START_VAL+2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.