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 x and y of 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
Interview Questions & Answers
What is the difference between a reference and a pointer in C++?
What is the difference between new and malloc in C++?
What is a memory leak in C++ and how to avoid it?
What is nullptr in C++? What is the difference from NULL?
What is RAII in C++?
What is the difference between unique_ptr, shared_ptr and weak_ptr?
What is const correctness in C++?