Re: Re: power operator (again)

From: Date: Sat, 21 Dec 2013 11:59:32 +0000
Subject: Re: Re: power operator (again)
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-70811@lists.php.net to get a copy of this message
On 21/12/2013 10:29, Robert Stoll wrote:
echo ( -3 * 2); // -6 $x = -3; echo $x * 2; // -6 -> does not behave like (-3) * 2
This is an extremely poor choice of example: (-3) * 2 and -(3*2) both evaluate to -6 anyway, since unary minus is effectively multiplication by -1, and therefore commutative with multiplication. However, the last line *does* behave like "(-3) * 2", because left operand of the * has already been calculated and stored in $x; it could have been calculated using "$x = 10 - 13", in which case you could see it as equivalent to "(10 - 13) * 2" - the brackets basically meaning "calculate this bit first before you even look at the rest of the expression".
Nope, that's not true. 1+2 is just already evaluated and the result was stored in $x rather than the expression.
That is exactly what I was trying to say: the expression $x * 3 does not need any rules of operator precedence, because it has only one operator (unless you count the $ sigil as an operator); if $x was previously assigned based on some other expression, the details of that expression are entirely irrelevant, only their answer matters. The point being that all this discussion of precedence only applies if the unary minus operator appears *in the same expression* as the power operator. But it's very unlikely that anyone would write "$sq = -3 ** 2" rather than just "$sq = 9"; more likely, they will write "$sq = $calculated_value ** 2", which has no ambiguity, and will work as expected for any value of "$calculated_value". Regards, -- Rowan Collins [IMSoP]

Thread (29 messages)

« previous php.internals (#70811) next »