Why does this if-statement combining assignment and an equality check return true?
Solution 1:
This has to do with operator precedence.
if (i = 1 && i == 0)
is not
if ((i = 1) && (i == 0))
because both &&
and ==
have a higher precedence than =
. What it really works out to is
if (i = (1 && (i == 0)))
which assigns the result of 1 && (i == 0)
to i
. So, if i
starts at 0
then i == 0
is true
, so 1 && true
is true
(or 1
), and then i
gets set to 1
. Then since 1
is true, you enter the if block and print the value you assigned to i
.
Solution 2:
Assuming your code actually looks like this:
#include <iostream>
using namespace std;
int main() {
int i = 0;
if (i = 1 && i == 0) {
cout << i;
}
}
Then this:
if (i = 1 && i == 0) {
evaluates as
if (i = (1 && i == 0)) {
and so i
is set to 1
.