V2620. MISRA. Value of a composite expression should not be cast to a different essential type category or a wider essential type.
This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
This diagnostic rule is relevant only for C.
The MISRA C standard defines its own type model, called the essential type model.
The conversion a composite expression's result to an essential type of a different category—or to a wider type—can cause the loss of the higher bit values.
The example:
int32_t foo(int16_t x, int16_t y)
{
return (int32_t)(x * y);
}
On typical platforms (x86/ARM), the int16_t
corresponds to the short
type. During the evaluation, short
expands to the int
type. However, on other platforms (for example, 16-bit microcontrollers), int16_t
may correspond to the int
. Thus, no expansion to 32 bit occurs, which may result in overflow in the multiplication.
The fixed code:
int32_t foo(int16_t x, int16_t y)
{
return (int32_t)x * y;
}
In this case, the expression is evaluated in a wider type, int32_t
.
The example:
int32_t sum(float x, float y)
{
return (int32_t)(x + y);
}
According to the essential type model, the expression's resulting type belongs to the real floating essential type, while the int32_t
type belongs to the signed essential type. Conversion the sum's result to an integer type causes the loss of precision. The result of adding two float
type numbers may also be greater than the maximum of the int32_t
type range.
The fixed code:
float sum(float x, float y)
{
return x + y;
}
To convert the expression result to the int
type, make sure to:
- check that the converted value is within the type range;
- use a function to round the result to the integer value.
Within the essential type model, the type of a composite expression is defined as if the no integer promotion to int
occurred.
This diagnostic is classified as:
|