This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).
This diagnostic rule applies only to code written in C. The C language allows much freedom in casting between arithmetic types, but it can also lead to hidden problems such as loss of sign, value, or precision.
The MISRA standard defines an essential type model, where variables can have the following types:
This model does not include pointers.
Following the essential type model can help to avoid many of the non-obvious issues mentioned above by assigning values of the same essential type to variables. Within this model, you are allowed to assign a value of a narrower essential type to a variable of a wider type. Implicit conversions between different essential types are forbidden.
Exceptions:
Example of non-compliant code:
typedef enum ENUM {ONE} ENUM;
void Positive(signed char x)
{
unsigned char uchr = x; // <=
unsigned short usht = x; // <=
unsigned int uit = x; // <=
unsigned long ulg = x; // <=
unsigned long long ullg = x; // <=
long double ld = 0.0;
double d = ld; // <=
float f = d; // <=
ENUM e = x; // <=
}
Fixed code:
enum {ONE = 1, TWO, THREE, FOUR, FIVE, SIX,
MUCH = 123123, MORE = 0x7FFFFFFF-1};
void Negative()
{
signed char c = ONE; // ok
signed short h = TWO; // ok
signed int i = THREE; // ok
signed long long ll = FOUR; // ok
unsigned char uc = FIVE; // ok
unsigned short uh = SIX; // ok
unsigned int ui = MUCH; // ok
unsigned long long ull = MORE; // ok
float f = 0.0f; // ok
double d = f; // ok
long double ld = d; // ok
ENUM e = c; // ok
}
This diagnostic is classified as:
|