V2531. MISRA. Expression of essential type 'foo' should not be explicitly cast to essential type 'bar'.

This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).

This diagnostic applies only to code written in C. A value of one essential type should not be explicitly cast to a value of another incompatible essential type.

The MISRA standard introduces the essential type model, where variables can have the following types:

This model does not include pointers.

The following table shows situations that developers should avoid:

V2531/image1.png

Exceptions:

Reasons for explicit type conversion are as follows:

For some reasons, casts from one essential type to another may be dangerous or meaningless, for example:

The following example will trigger the corresponding warnings:

enum A {ONE, TWO = 2};

float foo(int x, char ch)
{
    enum A a = (enum A) x;  // signed to enum, may lead to 
                            // unspecified behavior

    int y = int(x == 4);    // Meaningless cast Boolean to signed

    return float(ch) + .01; // Meaningless cast character to floating,
                            // there is no precise mapping between
                            // two representations
}

This diagnostic is classified as:

  • MISRA-C-10.5