When I run static code analysis it says:
Bitwise operator "~" has a signed operand "(uint8)0U".
How come this operand is signed while I am explicitly casting it to uint8 which is equivalent to unsigned char and also postfixing it with literal U which stands for unsigned integer?
0Uhas typeunsigned intand(uint8)0Uhas typeunsigned char, but like all types smaller thanint, it gets promoted tointin an expression context such as an operand to~.You should just remove the cast and use
~0U.Note however that on systems with 16- or 32-bit ints using two's complement representation (almost all current systems*):
~0Uhas typeunsigned intand evaluates to0xFFFFFFFF(0xFFFFifinthas 16 bits).~(uint8)0Uhas typeintand evaluates to-1, which has the same bit representation, whereas(uint8)~0Uevaluates to0xFFwith typeint.Depending on the context, one might be more appropriate than the other.
The static analyser underscores the often unexpected side effect of the C integer promotion rules...
* embedded 8- and 16-bit CPUs use 16-bit ints, whereas laptop, desktop and server main CPUs use 32-bit ints. Non two's complement representations for signed integers are obsolete and will be removed from the C2x of the C Standard