You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 8 Next »

The order in which operands in an expression are evaluated is undefined in C except at the sequence points.

Evaluation of an expression may produce side effects. At specific points in the execution sequence called sequence points, all side effects of previous evaluations have completed and no side effects of subsequent evaluations have yet taken place.

The following are the sequence points defined by C99:

  • The call to a function, after the arguments have been evaluated.
  • The end of the first operand of the following operators: logical AND &&; logical OR ||; conditional ?; comma ,.
  • The end of a full declarator: declarators;
  • The end of a full expression: an initializer; the expression in an expression statement; the controlling expression of a selection statement (if or switch); the controlling expression of a while or do statement; each of the expressions of a for statement; the expression in a return statement.
  • Immediately before a library function returns (7.1.4).
  • After the actions associated with each formatted input/output function conversion specifier.
  • Immediately before and immediately after each call to a comparison function, and also between any call to a comparison function and any movement of the objects passed as arguments to that call.

Between the previous and next sequence point an object can only have its stored value modified once by the evaluation of an expression. Additionally, the prior value can be read only to determine the value to be stored.

This rule means that statements such as:

i = i + 1;

are allowed while statements like:

i = i++;

are not allowed because it modifies the same value twice.

Non-compliant Code Example 1

In the following example, the order of evaluation of the operands to + is undefined.

a = i + b[++i];

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

a = 0 + b[1];

Or may also legally result in the following outcome:

a = 1 + b[1];

As a result, programs can not safely rely on the order of evaluatoin of operands between sequence pionts.

Compliant Solution 1

The following examples are independend on the order of evaluation of the operands and can only be interpreted in one way.

++i;
a = i + b[i];
a = i + b[i+1];
++i;

Non-compliant Code Example 2

There is no ordering of subexpressions implied by the assignment operator, so the behavior of the following statements is undefined:

i = ++i + 1;
a[i++] = i;

Compliant Solution 2

The following statements are allowed by the standard:

i = i + 1;
a[i] = i;

Non-compliant Code Example 3


Compliant Solution


References

  • No labels