#include /*************************************************** * Resetting a variable and returning its original * value * * Write a function that performs two operations: * * 1. Reset the argument to 0. * 2. Return the original value of the argument. * * For example, if * * m == 42, * * then after * * int n{ reset( m ) }; * * we should have * * m == 0 * n == 42. * * The parameter must be passed by reference because * the function must modify the variable supplied by * the calling function. * * The return value allows the function to also give * the original value back to the calling function. ***************************************************/ // Function declarations int main(); int reset( int &a ); // Function definitions int main() { int m{ 42 }; int n{ 91 }; std::cout << "m == " << m << " and n == " << n << std::endl; std::cout << "Resetting m and n..." << std::endl; std::cout << reset( m ) << std::endl; std::cout << reset( n ) << std::endl; std::cout << "m == " << m << " and n == " << n << std::endl; return 0; } /*************************************************** * reset * * Reset the argument to 0 and return its original * value. ***************************************************/ int reset( int &a ) { return 0; } // Hint: // // You must do three things, in the correct order: // // 1. Store the original value of a. // 2. Assign 0 to a. // 3. Return the stored original value. // // Why must you save the original value before // assigning 0 to a? // Solution: /* int reset( int &a ) { int const original{ a }; a = 0; return original; } */ /*************************************************** * Notice that original is declared const. * * Once we have copied the original value of a into * original, there is no reason for original to * change. * * The parameter a cannot be const because the * purpose of the function is to modify the variable * to which a refers. * * Thus, this function demonstrates two different * ways information can pass out of a function: * * - through a reference parameter; and * - through the return value. ***************************************************/