MISRA.ASSIGN.CONDAssignment operator is used in a condition. MISRA C 2012 Rule 13.4: The result of an assignment operator should not be usedC90 [Unspecified 7, 8; Undefined 18], C99 [Unspecified 15, 18; Undefined 32] [Koenig 6] Category: Advisory Analysis: Decidable, Single Translation Unit Applies to: C90, C99 AmplificationThis rule applies even if the expression containing the assignment operator is not evaluated. RationaleThe use of assignment operators, simple or compound, in combination with other arithmetic operators is not recommended because:
Examplex = y; /* Compliant */ a[ x ] = a[ x = y ]; /* Non-compliant - the value of x = y* is used */ /* * Non-compliant - value of bool_var = false is used but * bool_var == false was probably intended */ if ( bool_var = false ) { } /* Non-compliant even though bool_var = true isn't evaluated */ if ( ( 0u == 0u ) || (bool_var = true ) ) { } /* Non-compliant - value of x = f() is used */ if ( ( x = f ( ) ) != 0 ) { } /* Non-compliant - value of b += c is used */ a[ b += c ] = a[ b ]; /* Non-compliant - values of c = 0 and b = c = 0 are used */ a = b = c = 0; See alsoRule 13.2 MISRA-C 2004 Rule 13.1 (required): Assignment operators shall not be used in expressions that yield a Boolean value.This rule is also covered by MISRA.ASSIGN.SUBEXPR. [Koenig 6] No assignments are permitted in any expression which is considered to have a Boolean value. This precludes the use of both simple and compound assignment operators in the operands of a Boolean-valued expression. However, it does not preclude assigning a Boolean value to a variable. If assignments are required in the operands of a Boolean-valued expression then they must be performed separately outside of those operands. This helps to avoid getting "=" and "==" confused, and assists the static detection of mistakes. See "Boolean Expressions" in the glossary. ExampleFor example write: x = y; if ( x != 0 ) { foo(); } and not: if ( ( x = y ) != 0 ) /* Boolean by context */ { foo(); } or even worse: if ( x = y ) { foo(); } MISRA-C++ Rule 6-2-1 (required): Assignment operators shall not be used in subexpressions.This rule is also covered by MISRA.ASSIGN.SUBEXPR. RationaleAssignments used in a sub-expression add an additional side effect to that of the full expression, potentially resulting in a value inconsistent with developer expectations. In addition, this helps to avoid getting = and == confused. Examplex = y; x = y = z; // Non-compliant if ( x != 0 ) // Compliant { foo ( ); } bool b1 = x != y; // Compliant bool b2; b2 = x != y; // Compliant if ( ( x = y ) != 0 ) // Non-compliant { foo ( ); } if ( x = y ) // Non-compliant { foo ( ); } if ( int16_t i = foo ( ) ) // Compliant { } |