Today's face test, interview 10 nine wrong
This post was last edited by Vcshellcode on 2013-10-14 11:49:39
$a = 1;
$b = $a + $a + $a + +;
Echo $b; Output 3
echo "
";
$d = 1;
$c = $d + $d + +;
Echo $c; Output 3
?>
Most people answer:
$b = 5; Wrong.
$c = 3;
Someone here knows why the two results are the same.
Share to:
------Solution--------------------
There have been such posts, I was also a bit tangled. In the Official Handbook, the "direction of union of Operators" appears.
------Solution--------------------
I don't quite understand how C works. My own explanation is:
$a = 1;
$b = $a + $a + $a ++;//php first calculates $ A + $a (despite the high priority of $a++) and finally gets 3
$d = 1;
$c = $d + $d + +//php First calculates the $d++, in the calculation $d +
I don't know if that's right.
------Solution--------------------
References:
I don't quite understand how C works. My own explanation is:
$a = 1;
$b = $a + $a + $a ++;//php first calculates $ A + $a (despite the high priority of $a++) and finally gets 3
$d = 1;
$c = $d + $d + +//php First calculates the $d++, in the calculation $d +
I don't know if that's right.
I think the right, in fact, with parentheses can be more obvious to see the priority.
------Solution--------------------
($a + $a + +);
by execution order
1, $a + +
2. $a
Again by
$a = 1;
$b = $a + +;
Echo ($a. '-'. $b);
The result is $ A 2, $b 1 ($a + +) result is 1;
So $ A + $a + + = 2+1 is 3
Style 1
$b = $a + ($a + ($a + ($a + $a + +));
Execution order
1, ($a + $a + +)
2, ($a + ($a + $a + +))
//... Parentheses first
Since 1 is executed first, the value of a $ A variable is changed, and subsequent sequential executions are calculated as the changed value
Result: $b = 2 + (2 + (2 + (2 + 1));
Style 2
$b = $a + $a + $a + ($a + $a + +);
Equivalent to $b = (($a + $a) + $a) + ($a + $a + +);
Execution order
1, ($a + $a)
2, ($a + $a) + $a)
//...... Parentheses are preferred, and the same symbol is executed without parentheses
Execution result is $b = 1+1+1+ ($a + $a + +) i.e. $b=3+ (2+1)
At last
$b = $a + $a ++;//equivalent 1
$b = $a + $a + $a ++;//equivalent 2