PHP头条
热点:

PHP教程之变量互换


Attributed to Solomon W. Golomb; a method for swapping the values of two integer variables without using an intermediate variable (you can tell this dates from the Elder Days, when variables were expensive!). Thanks to PHP's syntax it's also a one-liner.
$a^=$b^=$a^=$b;
Okay, here's how it goes (yeah, like I need to make content-free posts just for the sake of an increment...).
First, simplify the line; noting that ^= is right-associative, which means that in that line the rightmost operator is evaluated first, that the assignment operators also return the value that they assign to their lvalue, and that foo^=bar is shorthand for foo=foo^bar:

Code:

$a^=$b^=$a^=$b;
$a^=($b^=($a^=$b));
$a=$a^b;
$a^=($b^=$a);
$a=$a^$b;
$b=$b^$a;
$a=$a^$b;

Recall what ^ does. Takes each pair of corresponding bits from its arguments (the internal binary representation of its arguments, that is), and xors them together to produce the corresponding bit of the result ("corresponding" means that the first bits of both arguments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and so on. This is why, as BuzzLY noted, it's important that both variables are the same size - demons probably start flying out of your nose if one of them runs out of bits to xor before the other. So to figure out what ^ does to a pair of variables, we only need to recap what it does to single bits


www.phpzy.comtrue/php/8800.htmlTechArticlePHP教程之变量互换 Attributed to Solomon W. Golomb; a method for swapping the values of two integer variables without using an intermediate variable (you can tell this dates from the Elder Days, when variables were expensive!). Thanks...

相关文章

    暂无相关文章
相关频道:

PHP之友评论

今天推荐