Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The conditional AND and OR operators (&& and ||, respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result of the conditional operator cannot be deduced solely by evaluating the first operand. Consequently, when the result of the conditional operator can be deduced solely from the result of the first operand, the second operand will remain unevaluated; its side - effects, if any, will never occur.

The bitwise AND and OR operators (& and |) do not exhibit this lack short-circuit behavior. Like Similar to most other Java operators, they evaluate both operands, first the left operand, and then the right. They return the same Boolean result as && and || respectively , but can have different overall effect effects depending on the presence or absence of side - effects in the second operand.

Consequently, either the & or the && operator can be used when performing Boolean logic. However, there are times when the short-circuiting behavior is preferred , and other times when the short-circuiting behavior causes subtle bugs.

Noncompliant Code Example (Improper &)

...

This noncompliant code example, derived from Flanagan \ [[Flanagan 2005|AA. Bibliography#Flanagan 05]\], has two variables , with no guarantees regarding their current values. The code must validate its data and then check whether {{array\[i\]}} is nonnegativewith unknown variables. The code must validate its data and then check whether array[i] is a valid index.

Code Block
bgColor#ffcccc

int array[]; // mayMay be null
int i;       // mayMay be aan validinvalid index for array
if (array != null &
    i >= 0 & i < array.length &
    array[i] >= 0) {
  // handleUse array
} else {
  // handleHandle error
}

Wiki MarkupThis code can fail due to the very errors it is attempting to prevent. When {{array}} is null or when {{i}} is not a valid index, the reference to {{array\[i\]}} will cause a {{NullPointerException}} or an {{ArrayIndexOutOfBoundsException}} to be thrown. This happens because the {{&}} operator fails to prevent evaluation of its right operand, even when evaluation of its left operand proves that the right operand is invalidfail as a result of the same errors it is trying to prevent. When array is NULL or i is not a valid index, the reference to array and array[i] will cause either a NullPointerException or an ArrayIndexOutOfBoundsException to be thrown. The exception occurs because the & operator fails to prevent evaluation of its right operand even when evaluation of its left operand proves that the right operand is inconsequential.

Compliant Solution (Use &&)

This compliant solution mitigates the problem by using &&, which causes the evaluation of the conditional expression to terminate immediately if any of the conditions fail, thereby preventing a potentially-invalid evaluation.runtime exception:

Code Block
bgColor#ccccff

int array[]; // mayMay be null
int i;       // mayMay be aan validinvalid index for array
if (array != null &&
    i >= 0 &&
   i i < array.length &&
    array[i] >= 0) {
  // handleHandle array
} else {
  // handleHandle error
}

Compliant Solution (Nested

...

if Statements)

This compliant solution uses multiple if statements to achieve the proper effect. While correct, it is more verbose and may be more difficult to maintain.

Code Block
bgColor#ccccff

int array[]; // mayMay be null
int i;       // mayMay be a valid index for array
if (dataarray != null) {
  if (i >= 0 && i < dataarray.length) {
    if (dataarray[i] !>= -10) {
      // handleUse array
    } else {
      // handleHandle error
    }
  } else {
    // handleHandle error
  }
} else {
  // handleHandle error
}

Although correct, this solution is more verbose and could be more difficult to maintain. Nevertheless, this solution would be useful if is preferable when the error-handling routines code for each potential failure condition failure were is different.

Noncompliant Code Example (Improper &&)

This noncompliant code example demonstrates code that compares two arrays for ranges of members that match. Here i1 and i2 are valid array indices in array1 and array2 respectively. It is expected that Variables end1 and end2 will point to the end are the indices of the ends of the matching ranges in the two arrays.

Code Block
bgColor#ffcccc

if (end1 >= 0 & i2 >= 0) {
  int begin1 = i1;
  int begin2 = i2;
  while (++i1 < array1.length &&
         ++i2 < array2.length &&
         array1[i1] == array2[i2]) {
    // arraysArrays match so far
  }
  int end1 = i1;
  int end2 = i2;
  assert end1 - begin1 == end2 - begin2;
}

The problem with this code is that when the first condition in the while loop fails, the second condition is does not executedexecute. That is, once i1 has reached array1.length, the loop may terminate terminates after i1 is executedincremented. Consequently, the apparent range over array1 is larger than the apparent range over array2, causing the final assertion to fail.

Compliant Solution (Use &)

This compliant solution mitigates the problem by judiciously using &, which guarantees that both i1 and i2 are incremented , regardless of the outcome of the first condition.:

Code Block
bgColor#ccccff
public void exampleFunction() {  
  while (++i1 < array1.length &     // notNot &&
         ++i2 < array2.length &&
         array1[i1] == array2[i2])

Compliant Solution (Nested If Statements)

This compliant solution uses multiple if statements to achieve the proper effect. While correct, it is more verbose.

Code Block
bgColor#ccccff

  while (true) {
    if (++i1 >= array1.length) break;
    if (++i2 >= array2.length) break;
    if (array1[i1] != array2[i2]) break;
    // rest of loop{
 //doSomething
  }
}

...

Applicability

Failure to understand the behavior of the bitwise and conditional operators can cause unintended program behavior.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

EXP07-J

low

unlikely

medium

P2

L3

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

...

...

[

...

...

...

]

§2.5.6.

...

, "Boolean

...

Operators

...

...

...

...

...

...

...

 

...

Image Added Image Added Image AddedEXP06-J. Use parentheses for precedence of operation      Expressions (EXP)      EXP08-J. Understand the evaluation of expressions containing non-short-circuit operators