synth
synth

Reputation: 65

Ternary operator in while loop

In this scenario, why is it that the output for i is 1 and not 0, since the while loop decrements the value for i two times from it's original value i=2?

#include<stdio.h>
int main(){
    int i=2,j=2;
    while(i+1?--i:j++)
         printf("%d",i);
    return 0;
}

Upvotes: 0

Views: 1257

Answers (1)

0___________
0___________

Reputation: 67835

It is because your complicated ternary operator can be reduced to

while(--i)

Explanation.

i+1 == 3, --i executes. i == 1 so the body of while loop executes (prints 1). now i+1 == 2, --i executes, i == 0 which is false in C and body of the while loop is being skipped.

i is decremneted twice - but printf executed only 1 time.

You can test it adding one more printf:

int main(){
    int i=2,j=2;
    while(i+1?--i:j++)
         printf("%d\n",i);
    printf("%d\n",i);
    return 0;
}

and the result will be as expected

1
0

Upvotes: 3

Related Questions