Monday, 2 September 2013

Php comparison precedence confusion

Php comparison precedence confusion

I'm reviewing my intern's code, and I stumbled upon something like this :
//k* are defined constants
if ($a == 0 & $b >= k0) $a = 1;
if ($a == 1 & $b >= k1) $a = 2;
if ($a == 2 & $b >= k2) $a = 3;
I thought he made a mistake, confusing & and && (I excepted a logical AND)
But, in fact, his code works as expected, and I can't understand why. In
my mind, >= has precedence on ==, which also has precedence on &
(reference).
So, I tested (1 == 0 & 1 >= 0) and it output 0. I expected 1, cause in my
mind, it was like:
1 >= 0 returns true,
Then 1 == 0 gives false,
So the expression is now (false & true), which I thought equal to (0 & 1)
Which equals 1...
So his & is acting like a ||.
Where am I wrong??

No comments:

Post a Comment