c – Using postfix increment in an L-value – Education Career Blog

Possible Duplicate:
In what order does evaluation of post-increment operator happen?

Consider the following snippet(in C):


uint8_t index = 10;
uint8_t arr20;

arrindex++ = index;

When I compile this with gcc, it sets arr10 to 10, which means that the postfix increment isn’t being applied until after the entire assignment expression. I found this somewhat surprising, as I was expecting the increment to return the original value(10) and then increment to 11, thereby setting arr10 to 11.

I’ve seen lots of other posts about increment operators in RValues, but not in LValue expressions.

Thanks.

,

Some standard language:

6.5 Expressions

1 An expression is a sequence of operators and operands that specifies computation of a
value, or that designates an object or a function, or that generates side effects, or that
performs a combination thereof.

2 Between the previous and next sequence point an object shall have its stored value
modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73)

3 The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

Paragraph 2 explicitly renders expressions of the form ai++ = i undefined; the prior value of i isn’t just being read to determine the result of i++. Thus, any result is allowed.

Beyond that, you cannot rely on the side effect of the ++ operator to be applied immediately after the expression is evaluated. For an expression like

ai++ = j++ * ++k

the only guarantee is that the result of the expression j++ * ++k is assigned to the result of the expression ai++; however, each of the subexpressions ai++, j++, and ++k may be evaluated in any order, and the side effects (assigning to ai, updating i, updating j, and updating k) may be applied in any order.

,

The line

arrindex++ = index;

causes undefined behaviour. Read the C standard for more details.

The essence you should know is: You should never read and change a variable in the same statement.

,

Assignment operation works from right to left, i.e. right part of expression calculated first and then it is assigned to the left part.

Leave a Comment