write a complete program that defines two functions that demonstrate the difference of the parameter passing methods as specified below, each of which simply triples the variable count defined in main. Then compare and contrast the two approaches. These two functions are
a.) function tripleByValue that passes a copy of count by value, triples the copy and returns the new value and
b) function tripleByReference that passes count by reference via a reference parameter and triples the original value of count through its alias (i.e., the reference parameter).
In the main function of the program,
assign any desired value to the variable that will be used as an actual parameter in the function call.
display the value of the actual parameter or argument before and after the function call. Do this for both functions.
#include <iostream>
using namespace std;
int tripleByValue(int count) {
// Return new value
return 3 * count;
}
int tripleByReference(int& count) {
// Triple the original value
count *= 3;
// Return the triple value
return count;
}
int main() {
int x = 42;
int newValue;
cout <<"Before call of tripleByValue x = " << x << endl;
newValue = tripleByValue(x);
cout << "Function returns " << newValue << ", and x = " << x << endl;
cout <<"Before call of tripleByReference x = " << x << endl;
newValue = tripleByReference(x);
cout << "Function returns " << newValue << ", and x = " << x << endl;
return 0;
}
Comments
Leave a comment