Discussion:
Q: Use the program, Passing-by-Value, on Ex5_02 of the text and the program, Passing-by-Reference, on Ex5_07 as a starting point
Write a similar program, but change the code to pass two variables to the function call rather than one.
Response the following questions after completing both programs:
- What is the purpose of the function header?
- How may you identify the body of a function?
- What does the return statement do?// Ex5_02.cpp
// A futile attempt to modify caller arguments
#include
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
}
// Ex5_07.cpp
// Using a 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
}