MISRA Discussion Forums
10.4 violation for u8b + 2 - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.10 The essential type model (https://forum.misra.org.uk/forumdisplay.php?fid=165)
+---- Thread: 10.4 violation for u8b + 2 (/showthread.php?tid=1558)



10.4 violation for u8b + 2 - fmteau - 18-01-2021

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.


RE: 10.4 violation for u8b + 2 - misra-c - 21-08-2021

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 )



RE: 10.4 violation for u8b + 2 - fmteau - 05-10-2021

Thanks for the clarification