0
#include <stdio.h>
#include <stdlib.h>

void main()
{
    int a[5] = {5,1,15,20,25};
    int i,j,m;

    i = ++a[1];
    j = a[1]++;
    m = a[i++];

    printf("%d %d %d ",i,j,m);
}

The output of above program is:

3 2 15,

I just want to know why? I am having trouble in understanding increment operator.

PageNotFound
  • 2,320
  • 2
  • 23
  • 34

1 Answers1

2

For example, a++ means first return a, then add 1 to a, while ++a means first add 1 to a, then return a.

So

i = ++a[1];
j = a[1]++;
m = a[i++];

equals to

//i = ++a[1];
a[1] = a[1] + 1;//a[1] = 2
i = a[1];//i = 2
//j = a[1]++;
j = a[1];//j = 2
a[1] = a[1] + 1;//a[1] = 3
//m = a[i++];
m = a[i];//m = a[2] = 15
i = i + 1;//i = 3

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

PageNotFound
  • 2,320
  • 2
  • 23
  • 34