3

I need to call a function which call a macro-function to change macro-value in runtime.

This code isn't compiled:

#define MY_MACRO 32
#define SET_MY_MACRO_VAL(IS_TRUE)(MY_MACRO=(IS_TRUE)?16:U32)

In function SET_MY_MACRO_VAL

> error: lvalue required as left operand of assignment

    #define SET_MY_MACRO_VAL(IS_TRUE)(MY_MACRO=(IS_TRUE)?16:U32)
                                          ^
    in expansion of macro 'SET_MY_MACRO_VAL'
         SET_MY_MACRO_VAL(True);
         ^
3
  • there are no macros at runtime. Macros are expanded even before compilation Commented Jun 5, 2018 at 9:00
  • Is IS_TRUE known at compile time? If not I'm afraid using the preprocessor is a non-starter Commented Jun 5, 2018 at 9:05
  • 2
    There are no such things as macro-functions or macro-variables. Commented Jun 5, 2018 at 9:10

1 Answer 1

3

Macro value are replaced BEFORE compile time by the preprocessor and do not exist at run time.

It is not a variable it is simply a way of using text for the value "32".

If you do this :

#define MY_MACRO 32
#define SET_MY_MACRO_VAL(IS_TRUE)(MY_MACRO=(IS_TRUE)?16:U32)

It will be expanded to this

#define MY_MACRO 32
#define SET_MY_MACRO_VAL(IS_TRUE)(32=(IS_TRUE)?16:U32)

What you can do is use a #define

#ifdef SET_MACRO_VAL_32
#define MY_MACRO 32
#else
#define MY_MACRO 16
#endif

Or use a conditionnal macro if you prefer

#if (IS_TRUE>0)
#define MY_MACRO 32
#else
#define MY_MACRO 16
#endif

Edit : In C++, you shouldn't really need macro though. You can use template and / or constexpr variable for compile-time value. In C++17 you can even use constexpr if.

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

3 Comments

..or not use macros at all
Yes but the question was about macro :). In C++ template and/or constexpr are way better and cleaner
one could also read the question as "how to call function to change a value at runtime" ;) dont worry, you got my upvote already

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.