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

yano
  • 4,827
  • 2
  • 23
  • 35
FreeDragon
  • 49
  • 2
  • 2
    Change the print to be more useful: `printf("X = %d\n", x);`. See what happens then. When `x` is zero, `x++` will be executed but the second half of the condition will evaluate to false too (because `x` is `1` by the time that happens). There is a sequence point between evaluating the LHS and the RHS of the condition. – Jonathan Leffler May 19 '23 at 16:00
  • 2
    when x is 0 "x++" is false, then x becomes 1 and it compares "x == 0", which is also false (after post increment on x) – Garr Godfrey May 19 '23 at 16:01
  • 1
    if you did `while (++x || x == 0)` you would get an infinite loop. – Garr Godfrey May 19 '23 at 16:02
  • 2
    For the first `while` test, `x` starts as -2 and becomes -1. For the second `while` test, `x` starts as -1 and becomes 0. For the third while test, `x` starts as 0 and becomes 1. This change occurs before the `x==0` condition is evaluated, so it's effectively testing `0 || 1 == 0`, which is false. – Tom Karzes May 19 '23 at 16:07

1 Answers1

5

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • @Garr Godfrey I am a beginner to coding and c language, so can you give me book names and internet sources to study more about logical operator short-circuiting,increment and sequence point. – FreeDragon May 19 '23 at 16:31
  • @FreeDragon -- [C Tag Info Page](https://stackoverflow.com/tags/c/info), [The Definitive C Book Guide and List](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – ad absurdum May 19 '23 at 19:58