3
#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.

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

When the following line is executed,

m = a[i++];

i is incremented again, making its value 3.

2 Comments

oh yes. Thank you and thts why m return a[2] and thats 15 as i++ is post increment. m is assigned the value before i is incremented. But then j must be equal to '1' as value will be assigned first and then it will increment isnt it ?
The line j = a[1]++; can be interpreted as j=a[1];a[1] = a[i]+1;. The value of the expression a[1]++, which is assigned to j, is the value of a[1] before a[1] is incremented.
0

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.

Comments

0

i = 3 because

i = ++a[1] => i = ++1 and so i,a[1] are both 2
m = a[i++] => i = 3 because of i++

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.