C++ – most efficient way of swapping values c++

cdoubleintperformanceprocessing-efficiency

I was wondering what the most efficient, in terms of operations, way of swapping integers is in c++, and why? Is something like:

int a =..., b = ...;
a = a + b;
b = a - b;
a = a - b;

more efficient than using a temporary? Are there any other more efficient ways? (not asking for just other ways to swap the ints) and why would they be more efficient?

Best Answer

Assigning values is always faster than doing arithmetic operations.

C++ implementation for std::swap is

template<typename T> void swap(T& t1, T& t2) {
    T temp = std::move(t1); // or T temp(std::move(t1));
    t1 = std::move(t2);
    t2 = std::move(temp);
}

So to use a temporary variable is better than doing arithmetic trick.
And to use std::swap is even better because To reinvent the wheel in programming is never a good idea