Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c while loop entry

Tags:

c

while-loop

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

like image 439
harsha Avatar asked Nov 22 '25 09:11

harsha


1 Answers

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
like image 84
Vladimir Avatar answered Nov 24 '25 22:11

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!