Issue
I'm solving some exam questions, and I came across this one and I just don't get it.
int main()
{
int a[3+2] = {1, 2, 3}, i;
for(i = 0; a[i++]++;)
printf("%d", a[i]);
return 0;
}
Why is output of this code 2 3 0? I tried few ways of thinking but cant undertsand it.
Solution
In first iteration, a[i++]++
will do two things:
- Return value of
i
and increment it (first++
), thus leaving us witha[0]
(i
initialised as 0) as of now, - Now coming to the
a[0]
, it's post-incremented again (second++
), so this finally returnsa[0]
and then increments it.
So for the first iteration, the value returned in for
's condition is a[0]
which is 1, thus the loop will proceed to its body.
Coming to the body of our for loop, we now have two changes from the above statement, i
and a[i]
both incremented, so we have i = 1
and a[0] = 2
(a[0]
was incremented by 1, remember the outer ++
).
Continuing in the same fashion, we will move on to i = 2, a[1] = 3
(a[1]
was 2 but post-incremented, so became 3).
After this, again coming back to the loop's conditional, we have i
(=2) and a[i]
(=3) both post-incremented again, so the value returned will be a[i]
that is a[2]
(since i
is 2 as of now, now it is incremented after being returned), so i
would be 3 in the next statement inside for loop's body, which would make the array element as a[3]
that is 0 (that's why you get 0
in the last iteration).
Since i = 3
and from the array declaration, we have the default value of a[3]
as 0, it gives i = 3
, a[i] = a[3] = 0
in the next iteration.
Again coming back to the loop conditional, it will return a[i]
which at this point is a[3]
that is 0, thus failing the condition and hence halting the loop. Hence, you don't print anything afterwards.
Answered By - Jarvis Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.