-4

I tried out x+=1, x=x+1 inside the while loop's condition.

x = 0 // Initial value of x

1st case

while(x+=1 && x < 5){
    cout << x << endl;
}

2nd case

while(x=x+1 && x < 5){
    cout << x << endl;
}

The first case and second case are puzzling. What is the difference in the behavior of x+=1 and x=x+1 that both go into infinite loop (Because of short circuiting). But the value of x in the 1st case is stuck at 1.

Any thoughts ?

According to Is x += 1 more efficient than x = x + 1?, most compilers (good) optimize and do the exact same thing.

Compiler that I am using - gcc version 5.4.0

Community
  • 1
  • 1
pmuntima
  • 640
  • 5
  • 13

2 Answers2

5

Your bewilderment stems from a lack of parentheses. Your expressions are, in order, equivalent to the following:

(x++) && (x < 5)     // First case
x+=(1 && (x < 5))    // Second case
x=((x+1) && (x < 5)) // Third case

Along with implicit conversions and so on, this yields the behavior you are seeing.

This is why we use parentheses, and enable warnings when compiling.

You
  • 22,800
  • 3
  • 51
  • 64
0

x++ is an expression that increments x; its value is the old value of x. So with this code

int x = 0;
std::cout << x++ << 'n';

the output will be 0. Try it.

In the expression x++ && x < 5, x++ has the value 0, and 0 is treated as false. It's the left-hand side of the && operator, and because it's false, the right-hand side is not evaluated; the value of the expression is false. Try it.

The rest of the examples all increment the value of x, so in the test, the value of x is 1, which is treated as true for the && operator. That's the difference between the x++ in the first example and the x += 1 and the x = x + 1 in the second and third. To make the first one act like the others, change it to ++x && x < 5. In that case, ++x increments x, and the value of the expression is the result of the increment. So with

int x = 0;
std::cout << ++x << '\n';

the output will be 1. Try it.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165