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.14.1 - The right-hand operand of a logical && or || operator should not contain persistent side
effects [1]
Category: Advisory
Analysis: Undecidable,System
Rationale
The evaluation of the right-hand operand of the && and || operators is conditional on the value of the left-hand
operand. If the right-hand operand contains side effects then those side effects may or may not occur, which may be contrary to
developer expectations.
If evaluation of the right-hand operand would produce side effects which are not persistent at the point in the program where the
expression occurs then it does not matter whether the right-hand operand is evaluated or not.
The term persistent side effect [1] is defined in [[|glossary:chapter:Appendix]].
Example
uint16_t f( uint16_t y ) // The side effects within f are not
{ // persistent, as seen by the caller
uint16_t temp = y;
temp = y + 0x8080U;
return temp;
}
uint16_t h( uint16_t y )
{
static uint16_t temp = 0;
temp = y + temp; // This side effect is persistent
return temp;
}
void g( bool ishigh )
{
if ( ishigh && ( a == f( x ) ) ) // Compliant - f() has no persistent
{ // side effects
}
if ( ishigh && ( a == h( x ) ) ) // Non-compliant - h() has a persistent
{ // side effect
}
}
volatile uint16_t v;
uint16_t x;
if ( ( x == 0u ) || ( v == 1u ) ) // Non-compliant - access to volatile v
{ // is persistent
}
( fp != nullptr ) && ( *fp )( 0 ); // Non-compliant if fp points to a function
// with persistent side effects
if ( fp != nullptr )
{
( *fp )( 0 ); // Compliant version of the above
}
Glossary
[1] Persistent side effect
A side effect is said to be persistent at a particular point in execution if it might have an effect on the execution state at
that point. All of the following side effects are persistent at a given point in the program:
- Modifying a file, stream, etc.;
- Modifying an object, including via a pointer or reference;
- Accessing a volatile object;
- Raising an exception that transfers control outside of the current function.
When a function is called, it may have side effects. Modifying a file or accessing a volatile object are persistent as viewed by
the calling function. However any objects modified by the called function, whose lifetimes have ended by the time it returns, do not affect the
caller’s execution state. Any side effects arising from modifying such objects are not persistent from the point of
view of the caller.
The determination of whether a function has persistent side effects takes no consideration of the possible values for parameters or other
non-local objects.
Copyright The MISRA Consortium Limited © 2023