This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) guidelines for software development.
This rule applies only to C. Casting a composite expression's result to an essential type from a different category – or to a wider type – can cause the loss of the higher bit values.
Example:
int32_t foo(int16_t x, int16_t y)
{
return (int32_t)(x * y);
}
On some platforms (x86/ARM), the 'int16_t' corresponds to the 'short' type, and it is expanded to the 'int' type when the expression is evaluated. On other platforms (for example, 16-bit microcontrollers), 'int16_t' may correspond to the 'int' type and will not expand to 32 bits – and this may cause an overflow during the multiplication.
Below is a possible fix:
int32_t foo(int16_t x, int16_t y)
{
return (int32_t)x * y;
}
In this case, the entire expression is calculated in the 'int32_t' wider type.
Another 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 floating category, while the 'int32_t' type – to signed category of essential types. Casting 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 top limit of the 'int32_t' type's range.
The code below is a way to fix this:
float sum(float x, float y)
{
return x + y;
}
If further on you decide to cast the expression's result to the 'int' type, you need to do the following:
The Essential Type Model defines six categories:
In this model, the compound expression's type is defined in a way as if the result hadn't been expanded to 'int' – i.e. the integer promotion hadn't happened.
This diagnostic is classified as:
|