MISRA C:2012 Rule 10.3
The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category
Description
Note
Using Code Prover for checking coding rules is no longer supported. See Version History.
Rule Definition
The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category.
Rationale
The use of implicit conversions between types can lead to unintended results, including possible loss of value, sign, or precision.
For more information on essential types, see Essential Types in MISRA C Rules 10.x.
Polyspace Implementation
The rule checker reports a violation if the value of an expression is assigned to a variable with one of these data types:
Variable with a narrower essential type, for instance,
unsigned int
(32 bits) tounsigned short
(16 bits).Variable with a different essential type category, for instance,
_Bool
(essentially boolean) tounsigned int
(essentially unsigned).For more information on essential type categories, see
MISRA C:2012 Rule 10.1
.
Following the MISRA C™: 2012 specifications, the checker does not report a violation of this rule in these cases:
If an object is assigned the constant zero corresponding to its essential type. This acceptable zero value is
0
for integral types,0.0
for adouble
, and'\0'
forchar
.When a variable of aggregate type such as an array is initialized using the shorthand notation
{0}
, for instance:float dat2[3*3] = {0};
If the macros
TRUE
/true
andFALSE
/false
with the corresponding boolean value is assigned to abool
variable. Polyspace® reports a violation if these macros are spelled with mixed case.If a signed constant is assigned to an unsigned variable but the signed constant has the same representation as its unsigned equivalent. For instance, the checker does not flag statements such as:
unsigned int u = 1;
If an essentially real floating type expression is assigned to an object of essentially complex floating type when the size of the real type corresponding to the complex object can accommodate the real expression. For example:
The real type corresponding to the complex objectfloat32_t f32a; _Complex float32_t cf32a; cf32a = f32a;
cf32a
isfloat32_t
, which can accommodatef32a
. This assignment is compliant to this rule as an exception.
Code generation tools might use the boolean values true/false
with integer literals 1/0
interchangeably, resulting in violation of this rule. Because this rule is advisory when used in AGC
mode, you might want to justify such defects. See Annotate Code and Hide Known or Acceptable Results.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: The Essential Type Model |
Category: Required |
AGC Category: Advisory |