How to swap two numbers without using temp variables or arithmetic operations?

Viewed 59098

This equation swaps two numbers without a temporary variable, but uses arithmetic operations:

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

How can I do it without arithmetic operations? I was thinking about XOR.

10 Answers

C++11 allows to:

  • Swap values:

    std::swap(a, b);
    
  • Swap ranges:

    std::swap_ranges(a.begin(), a.end(), b.begin());
    
  • Create LValue tuple with tie:

    std::tie(b, a) = std::make_tuple(a, b);
    
    std::tie(c, b, a) = std::make_tuple(a, b, c);
    
Related