Use the program, Passing-by-Value, on pp. 261 of the text and the program, Passing-by-Reference, on pp. 268 as a starting point for this assignment.
Write a similar program, but change the code to pass two variables to the function call rather than one.
Note. Do not combine these programs into one program.
Here is p.261:
Passing - by - value One consequence of the pass - by - value mechanism is that a function can ’ t directly modify the arguments passed. You can demonstrate this by deliberately trying to do so in an example:
// Ex5_02.cpp
// A futile attempt to modify caller arguments
#include < iostream >
using std::cout;
using std::endl;
int incr10(int num); // Function prototype
int main(void)
{
int num(3);
cout < < endl < < "incr10(num) = " < < incr10(num) < < endl
< < "num = " < < num < < endl;
return 0;
}
// Function to increment a variable by 10
int incr10(int num) // Using the same name might help...
{
num += 10; // Increment the caller argument – hopefully
return num; // Return the incremented value
}
code snippet Ex5_02.cpp Of course, this program is doomed to failure. If you run it, you get this output: incr10(num) = 13 num = 3
Here is p.268:
Pass - by - reference Let ’ s go back to a revised version of a very simple example, Ex5_03.cpp , to see how it would work using reference parameters:
// Ex5_07.cpp
// Using an lvalue reference to modify caller arguments
#include
using std::cout;
using std::endl;
int incr10(int& num); // Function prototype
int main(void)
{
int num(3);
int value(6);
int result = incr10(num);
cout << endl << “incr10(num) = “ << result
<< endl << “num = “ << num;
result = incr10(value);
cout << endl << “incr10(value) = “ << result
<< endl << “value = “ << value << endl;
return 0;
}
// Function to increment a variable by 10
int incr10(int& num) // Function with reference argument
{
cout << endl << “Value received = “ << num;
num += 10; // Increment the caller argument
// - confidently
return num; // Return the incremented value
}
code snippet Ex5_07.cpp This program produces the output: Value received = 3 incr10(num) = 13 num = 13 Value received = 6 incr10(value) = 16 value = 16