Main Content

MISRA C:2023 Rule 10.5

The value of an expression should not be cast to an inappropriate essential type

Since R2024a

Description

Rule Definition

The value of an expression should not be cast to an inappropriate essential type.

Rationale

Converting Between Variable Types

 From
Boolean character enum signed unsigned real floating complex floating
To Boolean  AvoidAvoidAvoidAvoidAvoidAvoid
character Avoid    AvoidAvoid
enum AvoidAvoidAvoidAvoidAvoidAvoidAvoid
signed Avoid      
unsigned Avoid      
real floating AvoidAvoid     
complex floating AvoidAvoid     

Some inappropriate explicit casts are:

  • In C99, the result of a cast of assignment to _Bool is always 0 or 1. This result is not necessarily the case when casting to another type which is defined as essentially Boolean.

  • A cast to an essential enum type may result in a value that does not lie within the set of enumeration constants for that type.

  • A cast from essential Boolean to any other type is unlikely to be meaningful.

  • Converting between floating and character types is not meaningful as there is no precise mapping between the two representations.

Some acceptable explicit casts are:

  • To change the type in which a subsequent arithmetic operation is performed.

  • To truncate a value deliberately.

  • To make a type conversion explicit in the interests of clarity.

For more information on essential types, see Essential Types in MISRA C Rules 10.x.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

This example shows compliant casts between appropriate essential types and noncompliant casts between inappropriate types.

#include <stdbool.h>
#include <stdint.h>

enum vehicleType { CAR, TRUCK, MOTORCYCLE } vehicle;
enum colorType { RED, BLUE, GREEN } color;

void validateCasting() {
    ( int32_t ) 3U;       /*  Compliant */
    ( bool ) false;       /*  Compliant - 'false' from stdbool.h is essentially Boolean */
    ( bool ) 0;           /*  Compliant - by exception */
    ( bool ) 3U;          /* Noncompliant */

    ( int32_t ) vehicle;  /*  Compliant */
    ( enum vehicleType ) 3; /* Noncompliant */
    ( char ) color;       /*  Compliant */
}

Check Information

Group: The Essential Type Model
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a

expand all