Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing output after use of increment operator

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

like image 263
user3553190 Avatar asked Nov 27 '25 07:11

user3553190


1 Answers

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
like image 123
ajay Avatar answered Nov 28 '25 22:11

ajay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!