V2655. MISRA. The right operand of a logical '&&' or '||' operator should not contain persistent side effects.
The diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
The rule is relevant only for C.
The right operand of logical &&
and ||
operators should not contain persistent side effects.
According to the MISRA C standard, a side effect is considered persistent if it can influence the program state at a specific point in execution. Examples of such effects include:
- modifying a file;
- modifying (writing to) an object;
- using memory barriers;
- modifying the floating-point environment;
- accessing a
volatile
object.
The evaluation of the right operand depends on the result of the left operand:
- for the
||
operator, the right operand is evaluated only if the left operand returnsfalse
; - for the
&&
operator, the right operand is evaluated only if the left operand returnstrue
.
Thus, if the right operand contains side effects, they may not be applied.
The example:
volatile int counter;
void foo(int *ptr)
{
// ....
if (ptr != NULL && counter == 1)
{
return true;
}
// ....
}
The volatile
qualifier indicates the compiler that an access to this variable cannot be optimized, as it can be changed externally, for example, from another thread. The access to such objects can influence the program execution state and is therefore considered a persistent side effect.
The fixed example:
volatile int counter;
void foo(int *ptr)
{
// ....
if (ptr != NULL)
{
int tmp = counter;
if (tmp == 1)
{
return true;
}
}
// ....
}