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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.