+ 3

I have problem with incrementation inside if else statement in C++ quizes,i am really confused .

for eg int x=1,y=2; if(x++>=2 || ++y>=3) { cout<<y; } else { cout<<x; } please give and explain the output of above snippet.

5th Oct 2017, 5:23 AM
David Fernando
David Fernando - avatar
5 Antworten
+ 5
This outputs 3. x++>=2 This first gets the current value of x which is 1 and does the comparison. 1>=2 this is false and since an OR is used the 2nd condition will be checked also. x is incremented to 2 ++y>=3 This will first increment the value of y to 3 and then perform the comparison. 3>=3 this is true so the if statement is ran. cout<<y; // y has a value of 3
5th Oct 2017, 5:49 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Prefix ++ (before-name) takes precedence above all else. Postfix only gets excecuted last here, so its: if(1 >= 2 || 3 >= 3) // false OR true -> true { cout << "3"; }...
5th Oct 2017, 5:43 AM
Norbivar
Norbivar - avatar
+ 2
Then cout<<x; is ran where x will have a value of 2. As the first condition is false so the second will not be ran/checked (y is not incremented) and the else block is ran.
5th Oct 2017, 5:53 AM
ChaoticDawg
ChaoticDawg - avatar
0
thanks,what.will be the value of x in the end?
5th Oct 2017, 5:48 AM
David Fernando
David Fernando - avatar
0
if || operator is replaced with && then?
5th Oct 2017, 5:50 AM
David Fernando
David Fernando - avatar