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
- 1
In place of the first comment, write a function
swapValuesthat takes two references tointand swaps their values. - 2
In
main, in place of the comment between the two print lines, callswapValuesand pass it the variablesfirstandsecond. The program prints3 8and then8 3. - 3
Below
swapValues, write a functionsortPairthat also takes two references toint. When the first parameter holds a bigger number than the second, it callsswapValuesto swap them. That way, the first parameter always ends up with the smaller number. You can pass references on:swapValuesinsidesortPairchanges the variables frommain. In place of the last comment, callsortPair(x, y). The last line of the output then is4 9.