Reputation: 35
The outut of the code below is: 3 2 15
I was expecting 2 2 15
Why is this?
#include <stdio.h>
int main() {
int a[5] = { 5, 1, 15, 20, 25 };
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d", i, j, m);
return 0;
}
Upvotes: 0
Views: 121
Reputation: 144969
Lets proceed step by step:
#include <stdio.h>
int main() {
int a[5] = { 5, 1, 15, 20, 25 };
i = ++a[1]; // a[1] is incremented, becomes 2, i gets this value 2
j = a[1]++; // j gets a[1] which is 2, then a[1] is incremented and becomes 3
m = a[i++]; // m gets a[2] which is 15, i is incremented and becomes 3
printf("%d %d %d", i, j, m); // prints 3 2 15
return 0;
}
Upvotes: 0
Reputation: 98
Code
#include <stdio.h>
int main() {
int a[5] = { 5, 1, 15, 20, 25 };
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d", i, j, m);
return 0;
}
Lets go through this step by step..
a[1] is 1
i is ++1 that is.... 2
m is a[i] that is a[2] which is... 15
After this statement i++ is executed, so
after m = 15,
i becomes 3,
These values are printed using printf
Upvotes: 0
Reputation: 75
I want it to help you.
#include<stdio.h>
int main()
{
int a[5]={5,1,15,20,25};
i=++a[1]; // i = 2
j=a[1]++; // j = 2
m=a[i++]; // m = 15, i = 3
printf("%d %d %d",i,j,m);
return 0;
}
Upvotes: 0
Reputation: 884
becuase you increment it twice:
i=++a[1]; // i = 2
j=a[1]++;
m=a[i++]; // i = 3
printf("%d %d %d",i,j,m);
Upvotes: 1
Reputation: 145
The increment/decrement operators actually change the value of the object, not just return the resulting value. In the line m=a[i++];
you are incrementing i
again.
Upvotes: 2