Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assigning literal 0 to an unsigned variable
#1
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?
Reply
#2
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.
Posted by and on behalf of the MISRA C Working Group
Reply
#3
In that case, should the code look like so
Code:
unsigned u = 0U;
instead of
Code:
unsigned u = 0;
?
Reply
#4
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;
Posted by and on behalf of the MISRA C Working Group
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)