As the title says: Is the XOR Swap algorithm still viable? I know that temp-swaps are supposedly faster but the shear coolness of an XOR swap makes it more attractive to me. What do you guys/gals think?

For anyone that doesn't know what an XOR swap is here goes

int first = 10;
int second = 5;
cout<<"First: "<< first <<"\nSecond: "<< second << endl;
// XOR Swap
first ^= sec;
sec ^= fir;
fir ^= sec;
// Values are now switched
cout<<"First: "<< first <<"\nSecond: "<< second << endl;

It also works with a char array

cout<<"  XOR Swap"<< endl;
  cout<<"Before Swap:"<< endl;
  
  char x[6] = "shawn";
  char y[6] = "cplus";
  
  cout<<"X: "<< x << endl;
  cout<<"Y: "<< y << endl;
  // XOR Swap
  for(int i=0;i<7;i++)
          x[i]= x[i] ^ y[i];
  for(int i=0;i<7;i++)
          y[i]= x[i] ^ y[i];
  for(int i=0;i<7;i++)
          x[i]= x[i] ^ y[i];
  
  cout<<"\nAfter Swap:"<< endl;
  cout<<"X: "<< x << endl;
  cout<<"Y: "<< y << endl;

Dani AI

Generated

Short answer: it’s a neat trick but not a good default in modern C++ code. The XOR‑swap is historically interesting and sometimes useful at the assembly/register level, but for application code prefer the standard routine and readable code. This addresses the “coolness” from and the maintainability point by — use the well-defined standard swap unless you have a measured reason not to (std::swap on cppreference).

Key correctness and portability notes: XOR swapping only makes sense for plain bitwise-storage (integers/bitfields). It silently fails if the two operands are the same storage location (aliasing) — that will zero the value — so a runtime/address check would be required in high‑level code. It also doesn’t work for types with constructors/move semantics or for cases where arithmetic variants risk overflow. was right to point out that swapping two distinct variables with the same value still works; the real trap is aliasing (XOR swap — pitfalls on Wikipedia).

Performance myth-busting: seeing xor as an assembler mnemonic doesn’t prove it’s faster. Modern CPUs and compilers make plain moves extremely cheap (mov‑elimination), while the three-step XOR sequence creates strict data dependencies and higher latency; compilers often rewrite or eliminate XOR‑swap patterns. In practice std::swap (or compiler-generated moves) wins unless you’re in a very narrow, measured case. See expert microarchitecture/optimizer discussion for why XOR usually loses on contemporary x86-class CPUs. (’s hardware point is fair in spirit, but ’s question about instruction cost is precisely why XOR often underperforms.) (detailed discussion on StackOverflow).

Practical checklist: 1) Use std::swap for clarity and correctness. 2) Avoid XOR for non‑trivial types or when aliasing might occur. 3) Only consider XOR in hand‑tuned assembly or compiler backends after profiling and inspecting assembly on the target CPU. 4) If you must use it in C/C++, guard against identical addresses. For almost all application-level C++ code today, XOR‑swap belongs in the “fun trick” bin rather than production patterns.

Recommended Answers

All 6 Replies

>>What do you guys/gals think
I hate it because it does nothing more than obfuscate the program. Maintainability and readability are more important than cuteness.

the xor swap algorithm fails if you try to swap a variable with itself.
other swap algorithms using arithmetic operators fail if overflow or underflow occurs.
the correct way to swap two variables a and b of any type is std::swap(a,b). we would expect std::swap to be correct and to have the most efficient implementation possible for that type.
to me, std::swap is the coolest of the lot.

XOR is a assembler command. So... it executes very fast. Inside of C++ or worse C#, it will be a translation but you in C++, at least it will translate directly.

Compared to swapping by using 3 variables, this is akin to MOV operations on the processor which are generally more expensive than XOR operations.

But here's the deal by the time you program in C++ using XOR is not recommended unless you are performing special bitwise operations. The newer safer functions are highly optimized and can get the swapping job done more easily (less code).

As said before XoR fails if you try to swap a variable with itself. Not only that but it also fails if you try to swap variables with the same value. Try it and you'll see.

I personally use std:: Swap(a,b) even though I think it's slower..


Sorry, didn't read the rules before posting. u.u

uhm...

x = 10
y = 10
x = x ^ y # x => 0
y = x ^ y # y => 10
x = x ^ y # x => 10
puts "#{x}, #{y}" # => 10, 10

swapping two of the same values doesn't fail...

Compared to swapping by using 3 variables, this is akin to MOV operations on the processor which are generally more expensive than XOR operations.

Really? Why do you think so?

An assignment requires one fetch and one store. An XOR requires two fetches, one store, and the XOR operation itself. So why do you think that three XOR operations would be faster than three assignments?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.