Reputation: 774
int main() {
int i,j=6;
for(;i=j;j-=2)
printf("%d",j);
return 0;
}
This piece of code gives output 642 please explain me why this loop doesn't run infinitely and stops when j is non-positive
Upvotes: 0
Views: 84
Reputation: 106012
In C 0
is evaluated as false
and non-zero as true
. The controlling expression i = j
becomes false
when j = 0
and the loop will terminate.
The loop will go infinite if you change your program to
int i, j = 6;
i = j;
for(; i == j; j -= 2, i = j)
printf("%d",j);
Upvotes: 1
Reputation: 9642
for(;i=j;j-=2)
This is a for loop with no initial code, which on every iteration will assign j
to i
as the condition check, then at the end decrement j
by 2. Note that the value of an assignment expression is the value assigned, hence your i = j
expression will yield the value of j
.
So, what will happen cycle by cycle is as follows:
i
= 6, j
= 6i
= j
(6)j
(6)j -= 2
i
= j
(4)j
(4)j -= 2
i
= j
(2)j
(2)j -= 2
i
= j
(0)Upvotes: 0
Reputation: 121397
When j
becomes 0
the expression i=j
evaluates to 0
. Hence, the loop terminates.
Note that if j
were to start as negative number ( e.g. -1
)or as an odd number (e.g. 5
), then the condition will never evaluate to 0
and will result in an infinite loop.
Upvotes: 4