#include /*************************************************** * Swapping two local variables by reference * * Write a function that swaps the values of two * variables passed as arguments. * * Normally, function parameters are passed by value. * This means that the parameters are local copies * of the arguments supplied by the calling function. * * For example, if we declared * * void swap( int a, int b ); * * then changing a and b inside swap() would not * change the original variables. * * Instead, we will pass the parameters by reference: * * void swap( int &a, int &b ); * * A reference parameter refers to the original * variable supplied as the argument. Consequently, * assigning a new value to a or b changes the * corresponding variable in the calling function. ***************************************************/ // Function declarations int main(); void swap( int &a, int &b ); // Function definitions int main() { int m{ 42 }; int n{ 91 }; std::cout << "m == " << m << " and n == " << n << std::endl; std::cout << "Swapping m and n..." << std::endl; swap( m, n ); std::cout << "m == " << m << " and n == " << n << std::endl; return 0; } /*************************************************** * swap * * Swap the values of the two arguments. * * Because a and b are reference parameters, changes * made to a and b also change the variables passed * as arguments. ***************************************************/ void swap( int &a, int &b ) { return; } // Hint: // // Because a and b are references to the original // variables, you can treat them just as you would // treat two local variables that you wanted to swap. // // You will need a temporary variable: // // temporary = a // a = b // b = temporary // // Be careful to save the original value of a before // overwriting it. // Solution: /* void swap( int &a, int &b ) { int temporary{ a }; a = b; b = temporary; } */ /*************************************************** * Afterthought * * C++ already provides a function for swapping two * values. After including , we could write * * std::swap( m, n ); * * The purpose of writing our own swap() function * here is to demonstrate reference parameters and * how a function can modify variables belonging to * the calling function. ***************************************************/