Assigning literal 0 to an unsigned variable

6.10 Arithmetic Type Conversions

Moderators: misra-c, david ward

Post Reply
gs
Posts: 87
Joined: Thu Nov 18, 2004 1:39 am

Assigning literal 0 to an unsigned variable

Post by gs » Fri Jun 11, 2010 4:45 pm

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?

misra-c
Posts: 572
Joined: Thu Jan 05, 2006 1:11 pm

Re: Assigning literal 0 to an unsigned variable

Post by misra-c » Tue Jul 13, 2010 10:10 am

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

gs
Posts: 87
Joined: Thu Nov 18, 2004 1:39 am

Re: Assigning literal 0 to an unsigned variable

Post by gs » Tue Jul 13, 2010 2:54 pm

In that case, should the code look like so

Code: Select all

unsigned u = 0U;
instead of

Code: Select all

unsigned u = 0;
?

misra-c
Posts: 572
Joined: Thu Jan 05, 2006 1:11 pm

Re: Assigning literal 0 to an unsigned variable

Post by misra-c » Fri Jul 16, 2010 4:41 pm

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: Select all

unsigned u = (unsigned)0;
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “6.10 Arithmetic Type Conversions”