Why does this if-statement combining assignment and an equality check return true?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)