Swapping two integers without a temp variable

Started by
24 comments, last by onlinegmz 22 years, 5 months ago
quote:Original post by Anonymous Poster
USING A TEMP VARIABLE IS SLOWER THAN THE XOR THING...the xor intruction is only one cycle when done with the registers...the temp variable thing causes at least three instruction performed in memory which is avtually about 3cycles

If you''re doing it with registers why wouldn''t you use xchg? The XOR trick was because some older CPU''s didn''t have xchg, and they needed a quick way to swap registers. How can you be sure you''re data is always in registers anyway? Your compiler will figure it out and implement the swap in the quickest way possible according to the situation, so you just use the temporary variable.

[Resist Windows XP''s Invasive Production Activation Technology!]
Advertisement
quote:Original post by Oluseyi
--- quote ---
Dangerous. You have to be sure you are not swapping the same variables.
--- /quote ---

Fascinating:
int a = 4, b = 4;a = a ^ b; // a = 0b = a ^ b; // b = 4;a = a ^ b; // a = 4  

Appears to still work...


I wanna work for Microsoft!

Void said ''the same variable'', you''re using two different variables.

int a = 4;swap(a,a); 

would become:
int a = 4;a = a ^ a; // a = 0a = a ^ a; // a = 0a = a ^ a; // a = 0 
Oh, that''s what he meant! Well, the programmer who''d explicitly do that would need to be especially stupid. However, I can see how that could occur using references... good point.


I wanna work for Microsoft!
I think these methods will work, and they''re both pretty fast.


a = a - b;
b = a + b; // b = (a-b) + b = a
a = b - a; // a = a - (a - b) = b


or you can use xor:
(this is just in pseudo-code)

a = a xor b;
b = a xor b; //b = (a xor b) xor b = a
a = a xor b; //a = (a xor b) xor a = b
AH! I have been reading this post thinking that ^ was the power sign. I was like, what''s wrong with all of these guys...that doesn''t work. Then I realized it was the XOR operator.
what is the point of doing this unless you are working in asm?

This topic is closed to new replies.

Advertisement