Evaluation Order

From Appmethod Topics
Jump to: navigation, search

Go Up to Expressions Index

The order in which the compiler evaluates the operands of an expression is not specified, except where an operator specifically states otherwise. The compiler will try to rearrange the expression in order to improve the quality of the generated code. Care is therefore needed with expressions in which a value is modified more than once. In general, avoid writing expressions that both modify and use the value of the same object. For example, consider the expression

i = v[i++];  // i is undefined

The value of i depends on whether i is incremented before or after the assignment. Similarly,

int total = 0;
sum = (total = 3) + (++total); // sum = 4 or sum = 7 ??

is ambiguous for sum and total. The solution is to revamp the expression, using a temporary variable:

int temp, total = 0;
temp = ++total;
sum = (total = 3) + temp;

Where the syntax does enforce an evaluation sequence, it is safe to have multiple evaluations:

sum = (i = 3, i++, i++); // OK: sum = 4, i = 5

Each subexpression of the comma expression is evaluated from left to right, and the whole expression evaluates to the rightmost value

The compiler regroups expressions, rearranging associative and commutative operators regardless of parentheses, in order to create an efficiently compiled expression; in no case will the rearrangement affect the value of the expression