Static analysis tool I use raises a warning for this code :
uint16 var1 = 1U;
uint16 var2 = ~var1;
I check MISRA C 2004 rules and I find 10.5 rule :
If the bitwise operators ~ and << are applied to an operand od underlying type unsigned char or unsigned short, the result shall be immediately cast to the underlying type of the operand.
Ok, it's not a problem, implicit cast is applied (I think "cast" means implicit or explicit cast). But 10.1 rule says :
The value of an expression of integer type shall not be implicitly converted to a different underlying type the expression is complex.
An previous example of complex operation are : ~u16a
I change my code to :
uint16 var1 = 1U;
uint16 var2 = (uint16) ~var1;
And I obtain another warning : I think conversion of int negative value to unsigned int value not safe. I check C99 standard (ISO C99) § 6.3.1.3 but I don't understand if conversion of int to unsigned short are clearly specified.
In EmbeddedGurus article I read :
c = (unsigned int) a; /* Since a is positive, this cast is safe */
My questions :
- Have explicit conversion from signed int to unsigned short unspecified behavior ?
- If yes, how to use complement operator with unsigned short in safe way ?