Search code examples
c++floating-pointswapxor

C++ XOR swap on float values


Is it possible to use XOR swapping algorithm with float values in c++?

However wikipedia says that:

XOR bitwise operation to swap values of distinct variables having the same data type

but I am bit confused. With this code:

void xorSwap (int* x, int* y) {
   *x ^= *y;
   *y ^= *x;
   *x ^= *y;
}

int main() {

   float a = 255.33333f;
   float b = 0.123023f;
   xorSwap(reinterpret_cast<int*>(&a), reinterpret_cast<int*>(&b));
   std::cout << a << ", " << b << "\n";

   return 0;
}

it seems to work (at least under gcc), but I am concerned if such a practice is allowed if needed?


Solution

  • Technically, what you ask is possible but, as clearly commented by IInspectable, it causes UB (Undefined Behaviour).
    Anyway, I do suggest you to use std::swap instead, it's a template often specialized for specific data types and designed to do a good job.