Versions Compared

Key

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

...

This rule means that statements such as

Code Block
bgColor#ccccff
langcpp
i = i + 1;
a[i] = i;

are allowed, while statements like

Code Block
bgColor#FFcccc
langcpp
/* i is modified twice between sequence points */
i = ++i + 1;  

/* i is read other than to determine the value to be stored */
a[i++] = i;   

...

Programs cannot safely rely on the order of evaluation of operands between sequence points. In this noncompliant code example, the order of evaluation of the operands to the + operator is unspecified.

Code Block
bgColor#FFcccc
langcpp
a = i + b[++i];

If i was equal to 0 before the statement, the statement may result in the following outcome:

Code Block
bgColor#FFcccc
langcpp
a = 0 + b[1];

Or it may result in the following outcome:

Code Block
bgColor#FFcccc
langcpp
a = 1 + b[1];

Compliant Solution

These examples are independent of the order of evaluation of the operands and can only be interpreted in one way.

Code Block
bgColor#ccccff
langcpp
++i;
a = i + b[i];

Or alternatively:

Code Block
bgColor#ccccff
langcpp
a = i + b[i+1];
++i;

Non-Compliant Code Example

Both of these statements violate the rule concerning sequence points stated above, so the behavior of these statements is undefined.

Code Block
bgColor#FFcccc
langcpp
i = ++i + 1;  // an attempt is made to modify the value of i twice between sequence points
a[i++] = i;   // an attempt is made to read the value of i other than to determine the value to be stored

...

These statements are allowed by the standard.

Code Block
bgColor#ccccff
langcpp
i = i + 1;
a[i] = i;

Noncompliant Code Example

The order of evaluation for function arguments is unspecified.

Code Block
bgColorFFcccc
langcpp
func(i++, i);

The call to func() has undefined behavior because there are no sequence points between the argument expressions. The first (left) argument expression reads the value of i (to determine the value to be stored) and then modifies i. The second (right) argument expression reads the value of i between the same pair of sequence points as the first argument, but not to determine the value to be stored in i. This additional attempt to read the value of i has undefined behavior.

...

This solution is appropriate when the programmer intends for both arguments to func() to be equivalent.

Code Block
bgColor#ccccff
langcpp
i++;
func(i, i);

This solution is appropriate when the programmer intends for the second argument to be one greater than the first.

Code Block
bgColor#ccccff
langcpp
j = i++;
func(j, i);

Risk Assessment

...