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:
b
to a
, storing the result in a
.b
from a
, which gives us the original value of a
, and store it in b
.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.
Answers to questions are automatically generated and may not have been reviewed.
This lesson demystifies references, explaining how they work, their benefits, and their role in performance and data manipulation
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course