Main Content

MISRA C:2012 Rule 10.4

Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category

Description

Rule Definition

Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category.

Rationale

The use of implicit conversions between types can lead to unintended results, including possible loss of value, sign, or precision.

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

Polyspace Implementation

The checker reports a violation of this rule if the two operands of an operation have different essential types. The checker message states the types detected on the two sides of the operation.

The checker does not report a violation of this rule:

  • If one of the operands is the constant zero.

  • If one of the operands is a signed constant and the other operand is unsigned, and the signed constant has the same representation as its unsigned equivalent. For instance, the statement u8b = u8a + 3;, where u8a and u8b are unsigned char variables, does not violate the rule because the constants 3 and 3U have the same representation.

These cases are not true violations based on the rationale behind the rule. For instance, if a signed constant has the same representation as its unsigned equivalent, there is no risk of the value, sign or precision loss that this rule seeks to avoid.

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

#define S64_MAX (9223372036854775807LL)
#define S64_MIN (-9223372036854775808LL)
long long input_s64_a, input_s64_b, result_s64;

void my_func(void){
   if (input_s64_a < S64_MIN + input_s64_b) { //Noncompliant: 2 violations
      result_s64 = S64_MIN;
   }
}

In this example, the type of S64_MIN is essentially unsigned. The value 9223372036854775808LL is one more than the largest value that can be represented by a 64-bit variable. Therefore, the value overflows and the result wraps around to a negative value, so -9223372036854775808LL is essentially unsigned.

The operation input_s64_a < S64_MIN + input_s64_b violates the rule twice.

  • The + operation violates the rule. The left operand is essentially unsigned and the right operand is signed.

  • The < operation also violates the rule. As a result of type promotion, the result of the + operation is essentially unsigned. Now, the left operand of the < operation is essentially signed but the right operand is essentially unsigned.

Check Information

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

Version History

expand all