Main Content

MISRA C++:2008 Rule 5-0-3

A cvalue expression shall not be implicitly converted to a different underlying type

Description

Rule Definition

A cvalue expression shall not be implicitly converted to a different underlying type.

Rationale

This rule ensures that the result of the expression does not overflow when converted to a different type.

Polyspace Implementation

Expressions flagged by this checker follow the detailed specifications for cvalue expressions from the MISRA™ C++ documentation.

The underlying data type of a cvalue expression is the widest of operand data types in the expression. For instance, if you add two variables, one of type int8_t (typedef for char) and another of type int32_t (typedef for int), the addition has underlying type int32_t. If you assign the sum to a variable of type int8_t, the rule is violated.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<cstdint>

void func ( )
  {
    int32_t s32;
    int8_t s8;
    s32 = s8 + s8; //Noncompliant
    s32 = s32 + s8; //Compliant
  }

In this example, the rule is violated when two variables of type int8_t are added and the result is assigned to a variable of type int32_t. The underlying type of the addition does not take into account the integer promotion involved and is simply the widest of operand data types, in this case, int8_t.

The rule is not violated if one of the operands has type int32_t and the result is assigned to a variable of type int32_t. In this case, the underlying data type of the addition is the same as the type of the variable to which the result is assigned.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b