简体   繁体   中英

c while loop entry

somebody please explain me why

int i=0,j=10;
    while(j>0,i++){
    printf("%d%d",i,j);
    j--;
}

will not work and

int i=0,j=10;
while(i++,j>0){
    printf("%d%d",i,j);
    j--;
}

works.

Also please tell me why

int i=0,j=10;
while(j>0,++i){
    printf("%d%d",i,j);
    j--;
}

gives an infinite loop ?

thanks and regards

harsha

In your while-loop condition you use comma operator, which evaluates its parameters and returns the second one. So in your examples:

while(j>0,i++) - returns i before it gets incremented; 
                 that is 0, so loop won't execute at all 

while(i++,j>0) - returns (j > 0) - runs as expected

while(j>0,++i) - returns i - will run until i overflows  max int value

Read up on the C comma operator . Basically it winds down to the fact that the comma operator returns the result of whatever is on the right side of the comma - so in your first example, i++ returns 0, and the loop ends. In the third case, ++i is never 0 (at least not for a long time) so you get the infinite loop. The middle case is ok, since the result of j>0 is returned from the comma operator, and your loop works as expected.

You're using the comma operator. The result of the comma operator is the second sub-expression. So j>0,i++ evaluates to i++ . i++ is initially 0, so the loop never executes.

Likewise, j>0,++i evaluates to ++i , which will be non-zero until you overflow, so it appears to loop forever (though really just for a long time).

i++,j>0 works because the last-subexpression is j>0 , which is the actual condition that you want. Note that even though the comma operator throws away the result of the first expression ( i++ , in this case) it still evaluates that sub-expression, and so you still get the side-effect (incrementing i ).

In these cases, you have expressions that include a comma operator. The comma operator evaluates its left operand, then its right operand. The result is that of the right operand.

For the moment, let's consider only your last question:

int i=0,j=10;
while(j>0,++i){
    printf("%d%d",i,j);
    j--;
}

This should not really be an infinite loop, though it may run just a bit longer than expected. Since the result of the comma operator is the result of the right operand, this is waiting for ++i to become 0. Since it's starting at 0, it's going to cycle though all possible values of an int before it terminates. With a 16-bit int , that would probably take a few minutes. With a 32-bit int , it's going to take quite a bit longer. With a 64-bit int , it would be an infinite loop for any practical purpose -- I'm pretty sure I'll die long before it could hope to finish at any rate...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM