When programming micro-controllers, there sometimes are registers that need to be read in order to reset some flags. These registers are memory mapped and are declared as pointers to volatile in the code.
Assume the next snippet as example:
typedef volatile struct _Ifx_SCU
{
...
uint32_t reg;
...
}Ifx_SCU;
#define MODULE_SCU ((*(Ifx_SCU*)0xF0036000u))
void foo(void)
{
...
MODULE_SCU.reg; /* Read required to reset bits in reg */
...
}
Here reg has to be read in order to reset it's bits, there is no other way to reset some bits other thatn reading them, So, MISRA rule checker is complaining that there is dead code and it's right.
My question is What would be an ALTERNATE way of reading and discarding **reg value in order to avoid having "dead code"?** Because using the method in the post Casting the results of a volatile expression to void which has a very similar situation, I still getting a MISRA c 2012 rule violation. I'm not able to change anything from the #define MODULE_SCU or the struct so a correct alternative method is the way to go.
I don't want to just silence the compiler casting to void as I read from this thread: What does void casting do? because if I cast to void then the optimizer may optimize away that read and that is not desirable.
Don't pay too much attention to the correctness of the snippet, I only included it to illustrate the question
The correct way to read an object and discard the result is:
(void)object;
The cast is actually not necessary, but might keep the compiler from complaining (not sure about MISRA actually). FYI: it is an expression-statement.
If object
is qualified volatile
, the access may not be optimized away by the compiler, as this keyword tells the compiler that there is a side-effect, even if the compiler does not see it. That the cast applies to the result of the expression (the "read"), not the object, so it does not remove the qualifier as your comment implies.
The MISRA-checker should not complain, as the line actually does something. (That is implied by the volatile
qualifier). If the tool complains anyway, trash it. Even more as this is not the first time you appear to have trouble with it.