I have the following static analysis report that the code is not compliant for MISRA-C rule 10.5 :
Results of ~ and << operations on operands of underlying types unsigned char and unsigned short should immediately be cast to the operand's underlying type
The code is :
unsigned val = ~0U;
From what i understand, the idea is to have to maximum value of an unsigned int
which can also be achieved by unsigned val = UINT_MAX;
from <limits.h>
.
However, i would like to know if there is something wrong with this code.
To me, 0U
is of type unsigned integer and has a value of 0
, then operator ~
is applied which gives a result of type unsigned int
with all bits set to 1
and finally it is copied to an unsigned int
.
I would say that no integer promotion happens here before the operator ~
because we already have an unsigned int
.
Moreover, the tool gives the same report somewhere else in the code :
uint16_t val2 = (uint16_t)(~0U); /* cast is explicit so what is wrong here ? */
I am not sure whether or not this code needs a fix for both "offending" lines.