There are some situations in C++ where certain parts of expressions may not be evaluated. If these sub-expressions contain side effects then those
side effects may or may not occur, depending on the values of other sub expressions. The operators which can lead to this problem are
||, where the evaluation of the right-hand operand is conditional on the value of the left-hand operand. The
conditional evaluation of the right-hand operand of one of the logical operators can easily cause problems if the developer relies on a side effect
Operations that cause side effects are:
- accessing a volatile object
- modifying an object
- modifying a file
- calling a function that performs any operations that cause changes in the state of the execution environment of the calling function.
This rule raises an issue when there is assignment or the use of the increment/decrement operators in right-hand operands.
Noncompliant Code Example
if ( ishigh && ( x == i++ ) ) // Noncompliant
if ( ishigh && ( x == getX() ) ) // Only acceptable if getX() is known to have no side effects
The operations that cause side effects are accessing a volatile object, modifying an object, modifying a file, or calling a function
that does any of those operations, which cause changes in the state of the execution environment of the calling function.
For the time being, this rule only check that there is no assignment or no use of increment/decrement operators made in right hand operands.
- MISRA C:2004, 12.4 - The right-hand operand of a logical && or || operator shall not contain side effects.
- MISRA C++:2008, 5-14-1 - The right hand operand of a logical && or || operator shall not contain side effects.
- MISRA C:2012, 13.5 - The right hand operand of a logical && or || operator shall not contain persistent side effects
- CERT, EXP02-C. - Be aware of the short-circuit behavior of the logical AND and OR