The logical AND and logical OR operators (
||, respectively) exhibit "short-circuit" operation. That is, the second operand is not evaluated if the result can be deduced solely by evaluating the first operand.
Programmers should exercise caution if the second operand contains side effects because it may not be apparent whether the side effects actually occur.
In the following code, the value of
i is incremented only when
i >= 0:
Although the behavior is well defined, it is not immediately obvious whether or not
i gets incremented.
Noncompliant Code Example
In this noncompliant code example, the second operand of the logical OR operator invokes a function that results in side effects:
malloc() is called only if
NULL when entering the
free() might be called with a pointer to local data not allocated by
malloc(). (See MEM34-C. Only free memory allocated dynamically.) This behavior is partially due to the uncertainty of whether or not
malloc() is actually called.
In this compliant solution, a second pointer,
q, is used to indicate whether
malloc() is called; if not,
q remains set to
free() is guaranteed to safely do nothing.
Failing to understand the short-circuit behavior of the logical OR or AND operator may cause unintended program behavior.
|Axivion Bauhaus Suite|
Could detect possible violations of this recommendation by reporting expressions with side effects, including function calls, that appear on the right-hand side of an
|LDRA tool suite|
The right-hand operand of a logical && or || operator shall not contain side effects
|SonarQube C/C++ Plugin|
|SEI CERT C++ Coding Standard||VOID EXP02-CPP. Be aware of the short-circuit behavior of the logical AND and OR operators|
|MITRE CWE||CWE-768, Incorrect short circuit evaluation|