This piece of code reports three misra c errors:
- Inappropriate macro expansion
- Function-like macro definition
- Macro parameter with no parentheses
The original code is:
#define Wait(a, b) \
if (READ(b+0x1U)) \
{ \
while ((a & Write(b))) \
{ \
/* Do nothing - Busy wait */ \
} \
}
Here READ(b) is a macro and Write(b) is a function with no Misra C error.
I have trying changing it to remove errors
#define Wait(a, b) \
if ((uint32_t)0U != READ((b)+0x1U)) \
{ \
while ((uint32_t)0U != ((uint32_t)(a) & Write((uint32_t)(b)))) \
{ \
/* Do nothing - Busy wait */ \
} \
}
But i am still getting the first two errors. What needs to be done to remove these Misra C errors.
There's a list of things macros are allowed to expand to, and an if block isn't one of them. I believe this is because it can cause confusion about the attachment of else clauses. More about that here. You can use this construct:
You should use a function instead of a function-like macro whenever you can. Without knowing what READ expands to I can't say if that's possible in this case. That would be the only way to get rid of the warning about that.
The third one you already figured out; you have to put parentheses around
a
andb
in the body. The idea here is that if you have code likex*2
in the macro and someone passes3+1
as x, without the parenthesis you'd get3+1*2
, which is 5, instead of(3+1)*2
, which is the 8 which was almost certainly intended.The only other thing I would have to say about your code is are you sure you want
&
there and not&&
?