Versions Compared

Key

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

...

Non-Compliant Code Example

In this non-compliant code example, the value of i is incremented only when i >= 0.

Code Block
bgColor#FFCCCC
enum { max = 15 };
int i = /* initialize to user supplied value */;

if ( (i >= 0 && (i++) <= max) ) {
  /* code */
}

It is unclear whether the value of i will be incremented as a result of evaluating the conditionAlthough the behavior is well-defined, it is not immediately obvious how this code behaves.

Compliant Solution

In this This compliant solution , the exhibits identical behavior is identical and clearly apparentbut is easier to understand.

Code Block
bgColor#ccccff
enum { max = 15 };
int i = /* initialize to user supplied value */;

if (i >= 0) {
  i++;
  if  (i <= max) {
    /* code */
  }
}

Non-Compliant Code Example

In this non-compliant code example, the second operand of the logical OR operator invokes a function that results in side effects.

Code Block
bgColor#FFCCCC

char *p;

if ( p || (p = (char *)malloc(BUF_SIZE)) ) {
  /* do stuff with p */
}
else {
  /* handle error */
   return;
}

Compliant Solution

This compliant solution exhibits identical behavior but is easier to understand.

Code Block
bgColor#ccccff

char *p;
if (p == NULL) p = (char *)malloc(BUF_SIZE);
if (p == NULL) {
  /* handle error */
  return;
}

/* do stuff with p */

Risk Assessment

Attempting to modify an object that is the second operand to the logical OR or AND operator may cause that object to take on an unexpected value. This can lead to unintended program behavior.

...