Swap two numbers using a reference function
Description: Write a function swap_values(int& a, int& b) which swaps two variables. Test it with 10 and 25, and compare it with std::swap.
Hint:
- A reference parameter works on the original variable.
Solution
#include <iostream>
#include <utility>
void swap_values(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 25;
swap_values(x, y);
std::cout << x << ' ' << y << '\n';
std::swap(x, y);
std::cout << x << ' ' << y << '\n';
}
Output
25 10
10 25
How it works
- Because the parameters are references, the function changes
xandyof main, not copies.
Read C++ References.
Learn more about the similar topics:
| Tutorials |
|---|
| C++ References and const References |
| C++ Pointers |
| C++ Dynamic Memory: new, delete and Smart Pointers |
| Exercises & Assignments |
|---|
| Swap two numbers using a reference function |
| Manage a resource with unique_ptr |