Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Corrected some text and examples, changed to Applicability, and updated the references to Java 7

...

Code Block
bgColor#ccccff
int array[]; // may be null
int i;       // may be a valid index for array
if (data array!= null) {
  if (i >= 0 & i < dataarray.length) {
    if (dataarray[i] != -1) {
      // use array
    } else {
      // handle error
    }
  } else {
    // handle error
  }
} else {
  // handle error
}

Nevertheless, this solution is preferable if the error-handling routines code for each potential condition failure were different.

...

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

...

Code Block
bgColor#ccccff
  while (++i1 < array1.length &     // not &&
         ++i2 < array2.length &&
         array1[i1] == array2[i2])

Compliant Solution (Nested if Statements)

This compliant solution uses multiple if statements to achieve the proper effect. Although 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
  }

...

Applicability

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

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

EXP54-JG

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

...