程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP教程之變量互換

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



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved