+ 1
How this C++ program is executed?
here in this program why not output is 1222 as all the variables are incremented...? #include <iostream> using namespace std; int main() { int x=1,y=1,z=1; cout<<(++x || ++y && ++z); cout<<x<<y<<z; return 0; } //output:- 1211 please explain in detail how this program execute step by step...
16 Antworten
+ 1
No, because || and && are of same precedence and read from left to right. So the whole part right from the || does not matter, even if there would be thousand other expressions :)
+ 3
cout<<(++x || ++y && ++z);
^It'll execute ONLY the ++x and prints 1.
cout<<x<<y<<z;
^x is now equal to 2, so it prints 2 and then it prints y & z which are both 1.
End result: 1211
+ 3
thanks Matthias 😊
+ 2
You're welcome Suraj... Oh wait, that's right, you didn't thank me for giving you the same answers first. ;)
+ 2
thank Fata1 Err0r for coming here and giving your explanation 😊
+ 2
@Suraj
lol Then it is my fault for not providing better clarity for you. Also, no need to apologize, I was only joking around with you. I'm a really lighthearted, joking type of individual, so don't take me too seriously in that regard.
I'm glad you were able to reach a place of understanding though and I hope that you have a smooth journey toward learning what you're learning. Best of luck to you bro!
+ 2
Fata1 Err0r once again thanks bro☺☺😂
+ 1
why increment of y and z didn't took place
+ 1
(++x || ++y && ++z)
^Basically, you're giving it a condition of ++x is true OR ++y is true AND ++z is true. ++x is true so it doesn't further check the condition; it never gets to the ++y && ++z part because it's not necessary for the condition to proceed as true.
+ 1
but since here ++y is there not x++ so shouldn't first increment be performed?
+ 1
Matthias what about && part?
since it is and operator so should here ++z also be performed?
+ 1
If the first part would be false however (try int x =0 and jus place x there, without increment), then it will be evaluated.
+ 1
yes I got this
+ 1
Fata1 Err0r I am really sorry for that.... but I didn't understood what you were said.. that was my understanding problem..
0
Because || is the logical or. If any of both parts is true, the whole expression is true.
Which means that if the first part is already true, you don't need to evaluate the second part anymore to save computation time.
Imagine that these could have some complicated function, which takes long to compute.
0
Besides of this, if the first part of && would be 0 (=false), then the second also won't get evaluated.
Try around with different values and you will see :)