MISRA C:2012 Rule 10.5
The value of an expression should not be cast to an inappropriate essential type
Description
Rule Definition
The value of an expression should not be cast to an inappropriate essential type.
Rationale
Converting Between Variable Types
From | ||||||||
Boolean | character | enum | signed | unsigned | real floating | complex floating | ||
To | Boolean | Avoid | Avoid | Avoid | Avoid | Avoid | Avoid | |
character | Avoid | Avoid | Avoid | |||||
enum | Avoid | Avoid | Avoid | Avoid | Avoid | Avoid | Avoid | |
signed | Avoid | |||||||
unsigned | Avoid | |||||||
real floating | Avoid | Avoid | ||||||
complex floating | Avoid | Avoid |
Some inappropriate explicit casts are:
In C99, the result of a cast of assignment to
_Bool
is always 0 or 1. This result is not necessarily the case when casting to another type which is defined as essentially Boolean.A cast to an essential enum type may result in a value that does not lie within the set of enumeration constants for that type.
A cast from essential Boolean to any other type is unlikely to be meaningful.
Converting between floating and character types is not meaningful as there is no precise mapping between the two representations.
Some acceptable explicit casts are:
To change the type in which a subsequent arithmetic operation is performed.
To truncate a value deliberately.
To make a type conversion explicit in the interests of clarity.
For more information on essential types, see Essential Types in MISRA C Rules 10.x.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Check Information
Group: The Essential Type Model |
Category: Advisory |
AGC Category: Advisory |