#include <stdio.h>
int main()
{
int x = -2;
while (x++ || x==0)
{
printf("X");
}
}
The output is coming as
XX
Why?
I am expecting this code to have gone into infinite loop as increment will make either side of logical OR to be true.
The logical OR operator guarantees that the left side will be fully evaluated, including any side effects, before the right hand side is evaluated (if at all). More formally, there is a sequence point between the evaluation of the left side and the evaluation of the right side.
If x is 0 when this condition is evaluated:
(x++ ||x==0)
The left side will evaluate to 0 i.e. false, and x is incremented to 1. Then because the left side is 0 the right side is evaluated. And since x is now 1 the right side also evaluates to 0, making the condition false and causing the loop to terminate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With