tags:

views:

61

answers:

3

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

Consider the following snippet(in C):


uint8_t index = 10;
uint8_t arr[20];

arr[index++] = index;

When I compile this with gcc, it sets arr[10] 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 arr[10] to 11.

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

Thanks.

+1  A: 

The line

arr[index++] = 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.

frast
why the C++ standard?
N 1.1
There are two `+` too much in your text ;-)
Jens Gustedt
This question is regarding C, specifically. The C standard may not define the behavior either, but I'm not sure where to look.
Spencer
Sorry i edited my answer. I meant the C99 standard
frast
I really do not know the details and I think it does not matter as long as you play by the rules.
frast
@Jens look at the question.
frast
@frast: I was talking of the same `++` as N 1.1, so it is ok now.
Jens Gustedt
Section 6.5.16 of the C99 standard(The Assignment Operator) says: "The order of evaluation of the operands is unspecified." Which would seem to support frast's answer.
Spencer
+1  A: 

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

gtikok
John Bode
+2  A: 
John Bode
Thanks for the detailed answer!
Spencer