Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is logic operator short circuiting here?

#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.

like image 335
FreeDragon Avatar asked Nov 29 '25 17:11

FreeDragon


1 Answers

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.

like image 111
dbush Avatar answered Dec 02 '25 05:12

dbush