Ask your own question, for FREE!
Computer Science 19 Online
OpenStudy (anonymous):

Someone help me with this code in C++ include #using namespace std; int main () { int x=0; int y=0; if (x++ && y++) { y+=2; } cout<

OpenStudy (konradzuse):

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?

OpenStudy (rsmith6559):

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.

OpenStudy (anonymous):

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.

OpenStudy (konradzuse):

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

OpenStudy (anonymous):

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.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!