This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 8.18.2 - The result of an assignment operator should not be used [2]
[expr.ass]
Category: Advisory
Analysis: Decidable,Single Translation Unit
Amplification
This rule applies to simple and compound assignments, built-in or overloaded, even if they occur in an infeasible path [1]. It does not
apply to assignments within an unevaluated operand.
Rationale
The use of assignment operators, simple or compound, in combination with other arithmetic operators is not recommended because:
- It can significantly impair the readability of the code;
- It introduces additional side effects into a statement, making it more difficult to avoid the undefined behaviour covered by
M23_065: MISRA C++ 2023 Rule 4.6.1.
Example
x = y; // Compliant
a[ x ] = a[ x = y ]; // Non-compliant - value of x = y is used
if ( bool_a = bool_b ) // Non-compliant - value of bool_a = bool_b is used
{ // (bool_a == bool_b was probably intended)
}
if ( uint8_t i = y ) // Rule does not apply - not an assignment operator
{
}
if ( ( 0u == 0u ) || ( bool_a = bool_b ) ) // Non-compliant - even though
{ // bool_a = bool_b is not evaluated
}
if ( ( x = f() ) != 0 ) // Non-compliant - value of x = f() is used
{
}
a[ b += c ] = a[ b ]; // Non-compliant - value of b += c is used
a = b = c = 0; // Non-compliant - values of c = 0, b = c = 0 are used
Glossary
[1] Infeasible path
Infeasible paths occur where there is a syntactic path to a code fragment, but the semantics ensure that the control flow path will not be
executed. For example:
if ( u32 < 0 )
{
// An unsigned value will never be negative,
// so code in this block will never be executed.
}
[2] Use / used / using
An object is used if:
- It is the subject of a cast; or
- It is explicitly initialized at declaration time; or
- It is an operand in an expression; or
- It is referenced.
A function is used as defined in M23_331: MISRA C++ 2023 Rule 0.2.4.
A type is used as defined in M23_005: MISRA C++ 2023 Rule 0.2.3.
Copyright The MISRA Consortium Limited © 2023