Pre increment vs Post increment in array

user2442489 picture user2442489 · Jun 1, 2013 · Viewed 44k times · Source

I am learning programming and I have started from C language. I was reading Let us C book. And I was going through this program in that book.

main( ) 
{ 
 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 ) ; 
}

My understanding was, it will print i as 2, j as 1 and m as 15

But somehow it is printing as i as 3, j as 2 and m as 15? Why is it so?

Below is my understanding-

b = x++;
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old value of ‘x’ is used.

b = ++y;
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the value of ‘y’ gets modified before using it in a expression.

Is there anything wrong in my understanding?

Answer

Eric Wich picture Eric Wich · Jun 1, 2013

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.