+ 6
If statement with or and increment operator
Confused why the code below prints out 84 instead of 85. The only reason I can figure is that the increment operator next to y does not execute because the statement is not true? int x=7, y=4; if(++x>6 || ++y<5) cout<<x<<y; else cout<<x*y;
10 ответов
+ 19
|| is a "short-circuit" OR. If the first condition (LHS) is found to be true, RHS will not be executed or checked, and the body will run directly.
In this case, only ++x>6 is executed and found to be true. The body executes, printing x and y.
You can try using the bitwise OR ( | ), which checks all conditions, and see the difference.
+ 3
Thank you!!
+ 2
As a complementary note from the standard n4296 §5.15 p.129
" 1. The || operator groups left-to-right. The operands are both contextually converted to bool [...]. It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees [left-to-right] evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.
2. The result is a bool. If the second expression is evaluated, every value computation and side effect ¹
associated with the first expression is sequenced ² [before] every value computation and side effect associated with the second expression. "
And since the right-hand side of the || operator has no effect at all and assuming if the left-hand side become false it always gets evaluated to false, there's no logical reason to make it as part of the evaluation unless for obfuscationism!
_____
¹
https://en.m.wikipedia.org/wiki/Side_effect_(computer_science)
² https://en.m.wikipedia.org/wiki/Sequence_point
+ 2
8 : 4
+ 2
and the second condition can't be perform.
+ 1
If you use below code
int x=7, y=4;
if(++y<5 || ++x>6)
cout<<x<<y;
else
cout<<x*y;
so in this condition the L.H.S. in if( ) is false so R.H.S also gets executed which in turns results the you expected 85.
+ 1
if one first condition in "or" logical operator is true no need to check second condition
0
Philip bro (||) or operator checks for only 1 true statement ..so in your code first has been checked and results as true so it will be in printing X and Y ....if u want your output to be 85 use this if (++X>6 && ++Y>=5)
cout<<X<<Y ;
ok bro I hope u got it ..solve more and more problems to get benefited Ty ;)😄💪👉
0
If you use below code
int x=7, y=4;
if(++y<5 || ++x>6)
cout<<x<<y;
else
cout<<x*y;
so in this condition the L.H.S. in if( ) is false so R.H.S also gets executed which in turns results the you expected 85.
0
I do not understand...