Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
10.4 violation for u8b + 2
#1
Hello MISRA Bulletin Board,

I understand mixing signed and unsigned variables in arithmetic operations can really lead to unexpected results,
but I really fail to see what is the risk in adding a constant value of 2 (SLTR of signed char) to an unsigned 8-bit (char) variable.

Could you please elaborate what can possibly go wrong in this case?

Thanks in advance.
<t></t>
#2
The MISRA-C Working group aim for Essential Type model was to produce a model that could be applied consistently with minimal changes to existing code. Part of that model is the description in Appendix D of the resultant types for expressions, which aims to retain the signedness of the resulting expressions.
Code:
Consider "u8b + 2U"
  C Standard Type:
      u8b is first promoted to "signed int".  2U has the C standard type of "unsigned int"
      "signed int" + "unsigned int"  returns a C standard type of "unsigned int"
  MISRA Essential Type:   
      "unsigned char" + "unsigned char" returns an "unsigned char" essential type
     
Now consider "u8b + 2"
  C Standard Type:
      u8b is first promoted to "signed int".  2 has the C standard type of "signed int"
      "signed int" + "signed int"  returns a C standard type of "signed int"
 
MISRA Essential Type:   
      "unsigned char" + "signed char" returns ??
      The decision was to result to the C standard type when we have a mismatch in signedness.
      In this case "signed int".
As mentioned above the decision was that it was important to retain the same signedness of expression, especially when the result of an operator is used as an operand to another operator including assignment.  Consider the following example with a 16 bit integer type:
Code:
uint8_t u8 = 255U;
  ... u8 * 200 ...  // calculated in signed type
  The resultant value of 51000 exceeds the signed int range, thus giving an undefined result
 
  ... u8 * 200U ... // calculated in unsigned type
  The resultant value of 51000 will wrap round in a well defined manner ( giving 18232 )
Posted by and on behalf of the MISRA C Working Group
#3
Thanks for the clarification


Forum Jump:


Users browsing this thread: 1 Guest(s)