As others have mentioned, the behavior is undefined; by getting rid of the ++
operator, the following code would be well-defined (but still ugly as sin):
*((int *)marks + i) = i+1
Here's how it breaks down:
marks -- take the expression marks
(int *)marks -- cast it as a pointer to int
(int *)marks + i -- offset i integer elements from that address
*((int *)marks + i) -- deference the result to get an array element
*((int *)marks + i) = i+1 -- assign the result of i+1 to that element
This is essentially treating marks
as an array of int
, and assigning the result of i+1
to the i
'th element:
int *mp = (int *) marks;
mp[i] = i+1
The original expression was trying to do
mp[i++] = i+1
which invokes undefined behavior. Since the order in which i++
and i+1
are evaluated is not specified; the compiler is free to evaluate them in any order it feels like. Since i++
has a side effect (updating the value of i
), this means that you will get different results based on the platform, optimization settings, even the surrounding code. The language standard explicitly leaves the behavior undefined so that the compiler isn't required to handle this code in any particular way. You will get a result, but it's not guaranteed to be consistent from compiler to compiler (or even from run to run).