>
>
>
V2620. MISRA. Value of a composite expr…


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) 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:

  • check that the converted value is within the type's range;
  • use a function to round the result to the float value.

The Essential Type Model defines six categories:

  • boolean, for boolean true/false values: '_Bool';
  • signed, for signed integers or unnamed enums: 'signed char', 'signed short', 'signed int', 'signed long', 'signed long long', 'enum { .... };';
  • unsigned, for unsigned integers: 'unsigned char', 'unsigned short', 'unsigned int', 'unsigned long', 'unsigned long long';
  • floating, for floating point numbers: 'float', 'double', 'long double';
  • character, for characters: 'char';
  • named enum, for named sets of user-defined values: 'enum name { .... };'.

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:

  • MISRA-C-10.8