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
toa
, storing the result ina
. - Subtract the new
b
froma
, which gives us the original value ofa
, and store it inb
. - Subtract the new
b
froma
, which gives us the original value ofb
, and store it ina
.
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