Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting macro-variable-value in macro-function C++

Tags:

c++

macros

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);
         ^
like image 463
Kate Zz Avatar asked Aug 04 '26 13:08

Kate Zz


1 Answers

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.

like image 92
Clonk Avatar answered Aug 07 '26 02:08

Clonk



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!