Is it ok to assign a value in a C macro (i.e. have an lvalue in a macro)? For example, I would like to set a bit of a number to 1
based on the specified bit position. Is it ok to do this:
#define SET_BIT(data, pos) ((data) |= (1U << (pos)))
I've tested this and it works, but I feel like I'm walking on thin ice here and if I get used to macros like this, I would eventually run into problems.
CodePudding user response:
Macros won't exist once the preprocessor has finished expanding them in the code. If you have a statement like
SET_BIT(some_data, some_pos);
then it will be replaced by
((some_data) |= (1U << (some_pos)));
in the code that is parsed and compiled.
In short, doing assignments in macros is perfectly fine.
The problem with the first SET_BIT_TO_VAL
macro:
#define SET_BIT_TO_VAL(data, pos, val) (CLEAR_BIT(data, pos); (data) |= (1U << (pos)))
is that you put statements inside parentheses, like they were expressions. So that will not build.
The common way to group statements in a macro is to wrap them in a do { ... } while(0)
loop:
#define SET_BIT_TO_VAL(data, pos, val) \
do { \
CLEAR_BIT(data, pos); \
SET_BIT(data, pos); \
} while (0)