Evaluation Order

The C language does not guarantee the evaluation order of most expressions. Avoid writing constructs that depend on evaluation within an expression to proceed in a particular manner. For example,

i = 0;

func( i++, i++ );

.

.

.

func( int a, int b )

{

A compiler could evaluate this code fragment and pass 0 as a and 1 as b. It could also pass 1 as a and 0 as b and conform equally with the standards.

The C language does guarantee that an expression will be completely evaluated at any given “sequence point.” A sequence point is a point in the syntax of the language at which all side effects of an expression or series of expressions have been completed.

These are the sequence points in the C language:

The semicolon (;) statement separator

The call to a function after the arguments have been evaluated

The end of the first operand of one of the following:

Logical AND (&&)

Logical OR (||)

Conditional (?)

Comma separator (,) when used to separate statements or in expressions; the comma separator is not a sequence point when it is used between variables in declaration statements or between parameters in a function invocation

The end of a full expression, such as:

An initializer

The expression in an expression statement (for example, any expression inside parentheses)

The controlling expression of a while or do statement

Any of the three expressions of a for statement

The expression in a return statement