a[i] = i++;
Why does the above code not work?
What is wrong with above code? I am asking this question to improve my knowledge.
a[i] = i++;
Why does the above code not work?
What is wrong with above code? I am asking this question to improve my knowledge.
Because the ISO standard says that you are not allowed to change a variable more than once (or change and use one) without an intervening sequence point.
There is no sequence point between the use of i
in a[i]
and the change of i
in i++
.
The list of sequence points from C11 (not really changed that much since C99) are described in Annex C:
and 5.1.2.3 Program execution
states:
Evaluations A and B are indeterminately sequenced when A is sequenced either before or after B, but it is unspecified which.
The presence of a sequence point between the evaluation of expressions A and B implies that every value computation and side effect associated with A is sequenced before every value computation and side effect associated with B.
Section 6.5 Expressions
pretty much covers your exact case:
If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.
This paragraph renders undefined statement expressions such as
i = ++i + 1;
anda[i++] = i;
while allowingi = i + 1;
anda[i] = i;
.
It does work, but possibly not as expected. The problem is if it's not clear if i
gets incremented before the assignment and, if so, then a[i]
will reference the next item in the array.
Your question was very terse so you can expand on it if you want more information. But it's just hard to tell exactly which element of a
that syntax assigns to.