Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

The conditional AND and OR operators (&& and ||, respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result cannot be deduced solely by evaluating the first operand.

Exercise One should exercise caution when the operands following the first operand contain side effects. In the following code, the value of i is incremented only when i >= 0.

...

Wiki Markup
*EXP06-EX1:* Programmers who are aware of the short-circuit behavior often use it to their advantage, as in this example from Flanagan \[[Flanagan 2005|AA. Bibliography#Flanagan 05]\]:

Code Block
bgColor#ccccff
if (data != null && i < data.length && data[i] != -1) ... 

...

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Related Guidelines

CERT C Secure Coding Standard: EXP02-C. Be aware of the short-circuit behavior of the logical AND and OR operators
CERT C++ Secure Coding Standard: EXP02-CPP. Be aware of the short-circuit behavior of the logical AND and OR operators

Bibliography

Wiki Markup
\[[Flanagan 2005|AA. Bibliography#Flanagan 05]\] 2.5.6. Boolean Operators\[[JLS 2005|AA. Bibliography#JLS 05]\] Sections [15.23|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.23] "Conditional-And Operator &&" and [15.24|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.24] "Conditional-Or Operator ||"

...