Main Content

AUTOSAR C++14 Rule M5-0-8

An explicit integral or floating-point conversion shall not increase the size of the underlying type of a cvalue expression

Description

Rule Definition

An explicit integral or floating-point conversion shall not increase the size of the underlying type of a cvalue expression.

Rationale

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. For instance, in this example, the sum of two short operands is cast to the wider type int.

short op1;
short 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

void func() {
     short op1;
     short op2;
     int res;

     res = static_cast<int> (op1 + op2); //Noncompliant
     res = static_cast<int> (op1) + 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 int.

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

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a