Question

#include <stdio.h>

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\n",i,j,m);
}

Okay now the program compiles and runs fine. But the output which i get is 3 2 15 i.e i =3 , j=2, m = 15. I don't understand how come the value of i becomes 3 as a[1] i.e '1' when incremented must become 2. This is a 'trace the output' type of question. I'm using gcc.

Was it helpful?

Solution

I have written the values of the variables before and after the statement gets executes and all side effects have taken place.

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

// before : i is indeterminate, a[1] = 1
i = ++a[1];  
// after: i = 2, a[1] = 2

// before: j indeterminate, a[1] = 2
j = a[1]++;  
// after: j = 2, a[1] = 3

// before: m indeterminate, i = 2
m = a[i++];  
// after: m = a[2] = 15, i = 3

Therefore, the final values are

i = 3
j = 2
m = 15

OTHER TIPS

When the following line is executed,

m = a[i++];

i is incremented again, making its value 3.

On line 7, you have

i = ++a[1];

This increments a[1] (to 2), then assigns that to i.

Then on line 9, you have

m = a[i++];

This increments i (to 3), then assigns a[3] (15) to m.

i = 3 because

i = ++a[1] => i = ++1 and so i,a[1] are both 2
m = a[i++] => i = 3 because of i++
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top