chiragjn
chiragjn

Reputation: 774

Why is this not a infinite loop?

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

Answers (3)

haccks
haccks

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

slugonamission
slugonamission

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:

  • Assign i = 6, j = 6
  • Nothing for the initial for loop statement
  • i = j (6)
  • Print j (6)
  • j -= 2
  • i = j (4)
  • Print j (4)
  • j -= 2
  • i = j (2)
  • Print j (2)
  • j -= 2
  • i = j (0)
  • The above expression evaluated to 0, hence false, hence the loop terminates.

Upvotes: 0

P.P
P.P

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

Related Questions