Main Content

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

An explicit integral conversion shall not change the signedness of the underlying type of a cvalue expression

Description

Rule Definition

An explicit integral conversion shall not change the signedness of the underlying type of a cvalue expression.

Rationale

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

If you evaluate an expression and later cast the result to a different type, the cast has no effect on the underlying type of the evaluation (the widest of operand data types in the expression).. For instance, in this example, the sum of two unsigned int operands is cast to the type int.

unsigned int op1;
unsigned int op2;
int res;
res= static_cast<int> (op1 + op2);
However, a developer or code reviewer can expect that the evaluation uses the data type to which the result is cast later. For instance, one can expect a sum with the underlying type int because of the later cast.

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

typedef int int32_t;
typedef unsigned int uint32_t;

void func() {
     uint32_t op1;
     uint32_t op2;
     int32_t res;

     res = static_cast<int32_t> (op1 + op2); //Noncompliant
     res = static_cast<int32_t> (op1) +
           static_cast<int32_t> (op2); //Compliant

}

In this example, the first cast on the sum violates the rule but the second cast does not.

  • The first cast can lead to the incorrect expectation that the sum is evaluated with an underlying type int32_t.

  • The second cast first converts each of the operands to int32_t so that the sum is actually evaluated with the underlying type int32_t.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b