Swapping Values Using References

How can I use references to swap the values of two variables without using a temporary variable?

Swapping values using references without a temporary variable is a neat trick in C++. It's not only efficient but also demonstrates the power of references. Here's how you can do it:

#include <iostream>

void swap(int& a, int& b) {
  a = a + b;
  b = a - b;  // b is now original a
  a = a - b;  // a is now original b
}

int main() {
  int x{5};
  int y{10};

  std::cout << "Before swap: x = "
    << x << ", y = " << y << '\n';
  swap(x, y);
  std::cout << "After swap:  x = "
    << x << ", y = " << y << '\n';
}
Before swap: x = 5, y = 10
After swap:  x = 10, y = 5

Let's break down how this works.

First, we define a swap() function that takes two integer references as parameters.

Then, inside swap(), we perform three operations:

  • Add b to a, storing the result in a.
  • Subtract the new b from a, which gives us the original value of a, and store it in b.
  • Subtract the new b from a, which gives us the original value of b, and store it in a.

This method works because we're using references, so we're directly manipulating the original variables, not copies.

While this method is clever, it's worth noting that it can cause issues with overflow for very large numbers. In practice, the standard library's std::swap() function is often a better choice:

#include <iostream>
#include <utility>

int main() {
  int x{5};
  int y{10};

  std::cout << "Before swap: x = "
    << x << ", y = " << y << '\n';
  std::swap(x, y);
  std::cout << "After swap:  x = "
    << x << ", y = " << y << '\n';
}

std::swap() is more versatile as it works with any type, not just integers, and it handles potential edge cases more robustly.

References

This lesson introduces references, explaining how they work, their benefits, and their role in performance and data manipulation

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating an Array of References
Is it possible to create an array of references in C++?
References and Runtime Polymorphism
Can I use references with polymorphic classes to achieve runtime polymorphism?
Implementing Observer Pattern with References
How can I use references to implement a simple observer pattern in C++?
Reference vs Pointer to Const
What's the difference between a reference and a pointer to const in terms of function parameters?
Dangers of Returning References to Local Objects
What are the implications of returning a reference from a function that creates a local object?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant