output and misunderstanding in C++
I want to know why the output is (1), and why In the second assignment to variable b, the expression (i+=2) does not get evaluated. finally how does this program execute step by step? I am still a beginner.
`
int i = 0;
bool t = true;
bool f = false,
b;
b = (t && ((i++) == 0));
b = (f && (i += 2 > 0));
cout << i << endl;
`
Solution 1:
Because the &&
operator short-circuits and f
is false
, 1 += 2
is not being evaluated.
Since the entire expression can only be true
if both operands to &&
are true
, there is no need to evaluate (i += 2 > 0)
to determine that the value of the entire expression is false
. Given the lack of need to evaluate the second operand in this scenario, many programming languages guarantee that it will not be, including C and C++.
Be careful about using operands with side-effects in boolean expressions.