Pre increment vs Post increment in array

You hit the nail on the head. Your understanding is correct. The difference between pre and post increment expressions is just like it sounds. Pre-incrementation means the variable is incremented before the expression is set or evaluated. Post-incrementation means the expression is set or evaluated, and then the variable is altered. It’s easy to think of it as a two step process.

b = x++;

is really:

b = x;
x++;

and

b = ++x;

is really:

x++;
b = x;

EDIT: The tricky part of the examples you provided (which probably threw you off) is that there’s a huge difference between an array index, and its value.

i = ++a[1];

That means increment the value stored at a[1], and then set it to the variable i.

m = a[i++];

This one means set m to the value of a[i], then increment i. The difference between the two is a pretty big distinction and can get confusing at first.

Second EDIT: breakdown of the code

{ 
 int a[5] = { 5, 1, 15, 20, 25 } ; 
 int i, j, k = 1, m ; 
 i = ++a[1] ; 
 j = a[1]++ ; 
 m = a[i++] ; 
 printf ( "\n%d %d %d", i, j, m ) ; 
}

First:

i = ++a[1];

At this point we know a[1] = 1 (remember arrays are zero indexed). But we increment it first. Therefore i = 2.

j = a[1]++;

Remember we incremented a[1] before, so it is currently 2. We set j = 2, and THEN incremented it to 3. So j = 2 and now a[1] = 3.

m = a[i++];

We know i = 2. So we need to set m = a[2], and then increment i. At the end of this expression, m = 15, and i = 3.

In summary,

i = 3, j = 2, m = 15.

Leave a Comment