Talk:XOR swap algorithm

message: One paragraph in the article states that modern computer can do parallel computation and hence other swap algorithm may be faster than the XOR swap. Can someone explain how other swapping technique achieve parallel processing?
Take the vanilla approach for example.
var tmp1 <- var A
var A <- var B
var B <- var tmp1
regardless how you slice and dice the steps and memory access to the registers.  You still have to wait till the data transfer is complete before you can do the next step, even if you parallellize everything, these operation needs to be synchronized.  How would parallellism benefit?  Am I missing something?
: Here's a parallel version:
tmp1 <- A  ||  tmp2 <- B
B <- tmp1  ||  A <- tmp2
: -- Smjg 16:52, 12 Apr 2005 (UTC)
replies: text: Modern PC processors use register renaming. Therefore one register in your machine code may map to different physical registeres on the CPU. What matters is the dependency chain, that is what instructions depend on what other instructions not really what registers the programmer decided to call the result. Plugwash 10:29, 22 March 2006 (UTC)
thread_title:  Parallelisation 

message: Has anyone tried generalising the xor swap algorithm to cyclic permutations of three or more values?
It is possible to write the 3-cycle as five ^= statements
x ^= y;
y ^= x;
z ^= x;
x ^= z;
z ^= x ^ y;
but that's still six XOR operations, the same as swapping y<->z and then x<->y.
The interesting question is: Is it possible, for any n, to cycle n variables in place using fewer than 3n operations?
:You need a temporary register for storing the result of x ^ y. That means no register space is saved with this algorithm. --Graue 16:59, 18 September 2005 (UTC)
replies: text: By the commutativity of ^, z ^= x; z ^= y; is the same as z ^= x ^ y but avoids the temporary. Note that this then makes steps 3-5 the same as z<->x and as step 6 is z ^= y this means that you can write steps 3-6 as x ^= y; z<->x; and thus steps 1-6 as x<->y; z<->x; --80.175.250.218 12:15, 30 January 2007 (UTC)
thread_title:  Generalisation 

message: The caveat section says:
:One would assume that "swapping a variable with itself" effectively does nothing. The standard, intuitive algorithm that uses a temporary variable indeed comes out that way, but the XOR algorithm will xor the variable with itself, thus setting it to zero instead.
But this is wrong. Why don't we let A = B = 5, and see what happens:
#A := A xor B
#:A = 5 xor 5 = 0
#B := A xor B
#:B = 0 xor 5 = 5
#A := A xor B
#:A = 0 xor 5 = 5
Sure, there's a zero involved, but then the other property of XOR kicks in: a number XORed with 0 is the number you started with. I'm going to remove this section. MShonle 19:20, 14 August 2005 (UTC)
replies: text: Ah, looking at this a little further the case where this does break is when X and Y are aliased to the same memory location. A brief sentence could mention this, it doesn't need to be a section. MShonle 21:49, 14 August 2005 (UTC)
replies: text: Same variable means same memory location. Variable != value. Fredrik Johansson - talk - contribs 21:05, 17 January 2006 (UTC)

text: If we're going to have a whole article about that trick, and are going to get into the details of how it works, a section could easily  be dedicated to pointing out this flaw and working it out. Aliasing can occur in many situations, starting with random shuffles or sorting algorithms that use a sentinel. If your basic swap operation breaks in such cases, you're in for a world of hurt. This deserves more than just a passing mention. 199.111.193.97 04:48, 22 March 2006 (UTC)

text: I'm adding to the article to point out that the technique works even if the values are equal. It's not entirely clear from the article that value equality does not cause a problem; only aliasing does. -Chinmay  —Preceding unsigned comment added by 59.163.212.199 (talk) 08:43, 22 January 2008 (UTC)
replies: text: The article says both "However, the problem still remains that if x and y use the same storage location, the value stored in that location will be zeroed out by the first XOR instruction, and then remain zero..." and "...but first checks if their memory locations are distinct. This will remove problems caused by possible aliasing.".  There's also a subsection entitled "Aliasing".  This seems sufficient to me.  Oli Filth(talk) 09:46, 22 January 2008 (UTC)
thread_title: Caveat is wrong

message: When would you wish to swap values (say on an abacus)? Why can one not simply use B instead of A when needed?
Even when doing something like sorting, say:
a. check if A>B
b. if (a) then swap A,B
would need some register to store the result of A-B etc.
: Swap is the fundamental operation of sorting and other algorithms. —Ben FrantzDale 08:01, 9 February 2007 (UTC)
thread_title:  application? 

message: I'm going to edit this page shortly, but I thought I'd ask for some comments first.
Firstly, "Another advantage is that this algorithm is actually easier to remember and write without mistakes than the standard temporary variable swap algorithm.."
Surely that is not true? You have to remember to write first to the variable you copied into the temp. That is all you have to remember. Surely that's easier than what is written down.
Also, one very important thing I think is missing from this article is that when using an optimising compiler for a language like C, C++, java, then a temporary is almost always better.
This is because any optimising compiler will turn:
 int temp = a;
 a = b;
 temp = a;
into:
 Load a into register 1
 Load b into register 2
 Put register 1 into memory location b
 Put register 2 into memory location a
and if a and b are already in register, the "temporary variable swap" will turn into no code at all, and the compiler will just note that the locations of the variables have swapped around.
If it is ever better to swap the variables using the xor trick, then your compiler will know about it :) —Preceding unsigned comment added by Mrjeff (talk • contribs) 
:Yep. This is mentioned in the article, but I agree that it needs work. People keep adding little snippets of (mis?)information about assembly programming on various platforms, the history of C, and whatnot, which really ought to be consolidated into coherent sections of the article. For example, there could be one section on the abstract algorithm, one section on actual (documented) uses, and one section on reasons it should never be used. :)  However, it needs to be worked out so that people don't keep reading the first paragraph, discovering that it doesn't mention how many CPU cycles XOR swap takes on a PDP-42, and adding that in. There needs to be a clearly demarcated section for random machine-language exhumations. --Quuxplusone 05:52, 16 April 2006 (UTC)
thread_title:  Too much strength given to the xor swap. 

message: I propose to briefly summarize Swap by addition and subtraction as a section of the XOR swap algorithm article, and change the former into a redirect. The two methods share everything in common except for the particular arithmetic operator they choose to use.
At the same time, I propose to briefly summarize Subtraction edge as a section of the XOR linked list article, and change the former into a redirect. The two methods, blah, blah, blah.
Discuss here; I'll perform the merges in a few days if I hear no strong objections. --Quuxplusone 03:39, 28 November 2006 (UTC)
replies: text: Sure. Ideally this would involve renaming the articles to something more inclusive, but I can't think of anything. Deco 05:54, 28 November 2006 (UTC)

text: I don't think they should be merged as they are different methods after all.  Also, in practive, swap by addition and subtraction is not done.... However, it would be good to have them links under the see also section. --Cyktsui 23:33, 6 December 2006 (UTC)

text: XOR swapping is probably the more commonly discussed trick for swapping, and is also linked with XOR linked list. This page is also more likely to be found by someone searching for XOR and swap.  Does anyone have a historical reference for XOR swap?  Was XOR swap perceived before arithmetic swaps?  cbenz 14 Decemeber 2006 —The preceding unsigned comment was added by 66.92.80.211 (talk) 23:17, 14 December 2006 (UTC)
thread_title:  Proposed merge of XOR and ADD/SUB article pairs 

message: I've written a small note about this subject. It can be found here: Swapping the values of two variables. Do you think any of its content could be posted here?
Thanks.
--jff 15:32, 11 July 2007 (UTC)
replies: text: Looks to me like most of its content is posted here. :)  You demonstrate the XOR-swap trick and the "swap by addition and subtraction" trick, and mention that they can be generalized to use other operators instead of xor/add/subtract. That's basically what the Wikipedia article says at the moment, right? (The WP article goes off on other tangents also, of course.) --Quuxplusone 02:12, 12 July 2007 (UTC)
replies: text: Well, the XOR-swap trick in the note is just an instantiation. Why not use the "bitwise equality"? And why does the article mentions that XOR is commutative? It doesn't matter for the problem! The only important properties are associativity and unitpotency! Also, the note considers a generalisation: why use just one operator? IMO, I think it contributes with something new :) Thanks for your comment! --jff 12:13, 12 July 2007 (UTC)
thread_title:  Short note 

message: ...because they caused layout problems. If they were there for a good reason, please reinsert them, but try to do it in such a way that these problems don't return. Shinobu 17:02, 19 August 2007 (UTC)
thread_title:  Removed code-tags... 

message: I'm adding back in the "citation needed" tags around the section about reasons for using the xor swap. I've never come across a time when it's actually been used in practice, and I'm fairly confident that using it is always a bad idea. If you can give examples of when it's a good idea, by all means add in citations, and I will be satisfied.
:I've rewritten the section to reflect what I know about it, although I still don't have any references. It's rarely ever useful in practice and I'm not aware of any compiler that generates it. I think the section as it stood was quite misleading. Dcoetzee 08:33, 9 March 2009 (UTC)
thread_title:  Reasons for use in practice 

message: The introduction notes the variables need to be stored at "distinct memory addresses" but that is insufficient, for instance, if you have one 32 bit value at 0x0000 and the other on 0x0001 (counting 8 bit units) this does not work. --94.222.150.6 (talk) 01:09, 28 July 2010 (UTC)
replies: text: I have edited the article to clarify this; hopefully it satisfies you. , click on "prev" link to see changes made. PleaseStand (talk) 19:37, 28 July 2010 (UTC)
replies: text:  Very good, thank you! --94.222.150.6 (talk)  —Preceding undated comment added 03:36, 29 July 2010 (UTC)

text: No need to clarify anything, the whole concept of swapping two variables is undefined if the variables only partially overlap. Think about it. What value should each involved byte of memory take after the operation? -- Anonymous 22:01, 12 December 2010 (UTC)
replies: text: True (unless the result is stored in two new variables, even "worse" in terms of memory consumption than what the XOR swap attempts to avoid). I still don't see a problem with just including "distinct, non-overlapping" at the beginning of the article; it is just clarifying our assumptions, just as mathematicians include wording such as "for all real numbers" in theorems. PleaseStand (talk) 22:40, 13 December 2010 (UTC)
replies: text: I don't think we need the disclaimer.  It's no more necessary than a disclaimer that "both the memory addresses must exist"!  Oli Filth(talk|contribs) 23:22, 13 December 2010 (UTC)
replies: text: I think that now, most of us all agree that for practical purposes, "non-overlapping" is irrelevant, and I have returned the lead back to roughly how it was before this discussion started. PleaseStand (talk) 00:00, 14 December 2010 (UTC)
thread_title:  "distinct memory addresses" 

message: When I first encountered a question from a job interview in 2001,
I analysed the usefulness of the principle (http://sw-amt.ws/var-swap/VARIABLEN-TAUSCH.html in German).
The conclusion was, that the algorithm is only ever useful in assembler within a very constrained context.
In C it actually confuses the compiler and for interpreted languages it is outright preposterous.
To somewhat demonstrate the silliness of the entire XOR swapping, I used
a somewhat ironic technique to exchange two signals in hardware without crossing wires:
 
 X ---+----XOR-->  Q1 (==Y)
       \   /
        XOR
       /   \
 Y ---+----XOR-->  Q2 (==X)
The swapping property is derived directly by induction from the truth table:
X	Y	X^Y	Q1 = X^(X^Y)	Q2 = Y^(X^Y)
0	0	0  	0           	0
0	1	1  	1           	0
1	0	1  	0           	1
1	1	0  	1           	1
This technique successfully avoids crossing two wires:
 
X ---+   +--->  Y
      \ /
       /
      / \
Y ---+   +-->  X
Wolfmanx (talk) 00:42, 8 January 2017 (UTC)
thread_title:  Hardware example illustrating the inherent complexity of XOR swap