Reputation: 3346
Can anyone please help me understand how the output is 3 2 15
for the following code?
I am expecting output as: 2 2 15
because
a[1]
i.e 1
will get pre-incremented and i
will be assigned 2
,j
will also be assigned 2
because post increment is done and,m
, a[i++]
should be as a[2]
i.e 15
, since post increment is done and m
should be assigned 15
.Please help me if I am wrong.
#include<stdio.h>
int 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);
return 0;
}
Upvotes: 0
Views: 75
Reputation: 3724
a[1]=1;
i=++a[1]; //a[1] is pre-incremented by 1 so i=2;
j=a[1]++; // a[1] is post incremented by 1 so j=2;
m=a[i++]; // i is post incremented by 1 so m =a[2] so m=15
// as i was post incremented so i=2+1 in next step.
Upvotes: 0
Reputation: 12658
i=++a[1]; ==> ++a[1] == 2
i
gets the value of pre incremented of array a[1]
, which is 2
j=a[1]++; ==> a[1]++ == 2
Similarly j
becomes 2
but post incremented.
m=a[i++]; ==> a[3] == 15 /* Here i became 3*/
Here first i
which is already 2
incremented by 1
becoming 3
which is post incremented in next statement, resulting m
gets assigned with a[2]
which is 15
.
Upvotes: 0
Reputation: 128
The second menber of your array is 1. So doing i=++a[1]; translates to i=++1;. this is 2. J is the same thing ( in this case ). Then you take out the second value of your array (15) with "i" which is two, then you add one to "i". Resulting in i=3, j=2 and m=15.
Note : i=++1; is just to visualize what is happening, this shouldn't and can't be used.
Upvotes: 0
Reputation: 36438
int a[5]={5,1,15,20,25};
Increment a[1]
to 2
, and set i
to that
i=++a[1];
Set j
to a[1]
(2), then increment a[1]
to 3
j=a[1]++;
set m
to a[i]
(a[2]
, or 15), then increment i
to 3
m=a[i++];
Upvotes: 4
Reputation: 49803
Upvotes: 0
Reputation: 19864
i=++a[1]; /* a[1] = 1 and you have a pre-increment so */
i = 2;
j = a[1]++; /* a[1] = 2 and post-increment so j = 2 */
j= 2
m=a[i++]; /* m = a[2] = 15 and `i` is incremented later i = 3 */
m = 15
i = 3
So i=3 j = 2 and m = 15
Upvotes: 1