Someone help me with this code in C++
include
I believe it's because you said if(x++ && y++) That's just making x + 1, and I'm assuming it's doing nothing to y. You should say if x == 1 and y == 1, but what exactly are you trying to accomplish with this?
x++ and y++ are post incrementing. This means that the values of x and y are evaluated, and then x and y are incremented. This means that your if statement evaluates to false ( 0 & 0 = 0 logical false ). After the if, both x and y are incremented. Therefore the cout outputs 1 + 1 = 2. If you change " y += 2 " to " y += 3 ", it will become more apparent.
The sum is actually output as 1. x is 1 and y is 0. Why? Because of short-circuit evaluation. Inside the if statement, the left side of the && is evaluated (x++), it returns 0, which is false, and then it increments. The left side evaluates to false and so the right side is ignored.
^yeah exactly, because of that if(x++ && y++) I guess I didn't explain that now that I look back at what I said. ++i should return 1. ++i returns right away, while i++ returns after the for loop I believe...
Thank you :) Actually this was an exercise that my teacher gave us in the midterm.We have one month learning c++,and we are begginers so we have just learnt a few simple things ,and this exercise was very confused for us.
Join our real-time social learning platform and learn together with your friends!