Assigning literal 0 to an unsigned variable - 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: 2004 rules (https://forum.misra.org.uk/forumdisplay.php?fid=17) +---- Forum: 6.10 Arithmetic Type Conversions (https://forum.misra.org.uk/forumdisplay.php?fid=37) +---- Thread: Assigning literal 0 to an unsigned variable (/showthread.php?tid=742) |
Assigning literal 0 to an unsigned variable - gs - 11-06-2010 Should literal 0 be exempt from rule 10.1? True, rule 10.6 requires a 'U' suffix in this case. However, what about in regards to rule 10.1 by itself? Re: Assigning literal 0 to an unsigned variable - misra-c - 13-07-2010 Rule 10.6 does not apply. Literal 0 is an integer constant of type "signed int" (ISO:C90 6.1.3.2 - Semantics). Rule 10.6 is concerned with making the signedness of an integer constant explicit by including a "U" suffix when the constant is unsigned. It is only relevant to integer constants which are of a magnitude such that they are intrinsically unsigned and the rule has nothing to do with the context in which the constant is being used. For example: Assuming that int is implemented in 16 bits and a long in 32 bits, The constant "0" is of type signed int but the constant "0U" is of type unsigned int. However, the constants "3000000000" and "3000000000U" are both of type unsigned long. The constant "30000000000" would constitute a violation of Rule 10.6. Rule 10.1 addresses a different issue. It demands, among other things, that an expression which is assigned to an unsigned variable should itself be unsigned. This means that any constant or constant expression should itself be of "unsigned" type - including the constant '0'. The rationale behind this is that it is helpful to maintain consistent signedness when constructing arithmetic expressions, even if the omission of a 'U' suffix makes no difference to the result. Re: Assigning literal 0 to an unsigned variable - gs - 13-07-2010 In that case, should the code look like so Code: unsigned u = 0U; Code: unsigned u = 0; Re: Assigning literal 0 to an unsigned variable - misra-c - 16-07-2010 That is correct - the initialiser must have an unsigned type and a 'U' suffix is a neat way to do this for literals. There are other ways of achieving the same effect too, for example: Code: unsigned u = (unsigned)0; |