Swapping Two Variables
Swapping the values of two variables is a common task in programming, for example when sorting. Let's start in main, without a function. At first it looks easy:
int a = 3;
int b = 8;
a = b;
b = a;
std::cout << a << " " << b << std::endl;This prints:
8 8The statement a = b; overwrote the original value of a, the 3, and it was lost. It's like swapping the drinks in two full glasses: you need a third, empty one. In a program, that glass is a helper variable where you first store the original value of a:
int a = 3;
int b = 8;
int temp = a;
a = b;
b = temp;
std::cout << a << " " << b << std::endl;This prints:
8 3A function does it the same way, but it has to change both variables of the code that calls it. So both parameters are references. If one of them weren't a reference, the function would change only its copy, and the swap wouldn't work. The standard library has a ready-made swap function too, std::swap(a, b) (from the <utility> library). Now you know how it works inside.
References can do one more thing: a function can give back several results through them, while return gives back only one value. This function shares candies among children and stores in two references how many each child gets and how many are left over:
#include <iostream>
void share(int candies, int children, int& each, int& leftOver) {
each = candies / children;
leftOver = candies % children;
}
int main() {
int each = 0;
int leftOver = 0;
share(17, 5, each, leftOver);
std::cout << "Each child: " << each << ", left over: " << leftOver << std::endl;
return 0;
}This prints:
Each child: 3, left over: 2The function only reads the first two parameters, so they are ordinary parameters, and you can pass numbers to them. It writes to the last two, so they are references, and you must pass variables to them.
Instructions
In place of the first comment, write a function swapValues that takes two references to int and swaps their values.
In main, in place of the comment between the two print lines, call swapValues and pass it the variables first and second. The program prints 3 8 and then 8 3.
Below swapValues, write a function sortPair that also takes two references to int. When the first parameter holds a bigger number than the second, it calls swapValues to swap them. That way, the first parameter always ends up with the smaller number. You can pass references on: swapValues inside sortPair changes the variables from main. In place of the last comment, call sortPair(x, y). The last line of the output then is 4 9.
Start programming for free
2/10