willy the geek
Compile, execute, and run the "Try it Out" exercise, "Passing-by-Value. Verify that you are getting the same output. If you did not get the same output, discuss why do you think you got different output?
TRY IT OUT: Pass-by-Pointer
You can change the last example to use a pointer to demonstrate the effect:
// Ex5_03.cpp
// A successful attempt to modify caller arguments
#include <iostream>
using std::cout;
using std::endl;
int incr10(int* num); // Function prototype
int main()
{
int num {3};
int* pnum {&num}; // Pointer to num
cout << endl << "Address passed = " << pnum;
int result {incr10(pnum)};
cout << endl << "incr10(pnum) = " << result;
cout << endl << "num = " << num << endl;
return 0;
}
// Function to increment a variable by 10
int incr10(int* num) // Function with pointer argument
{
cout << endl << "Address received = " << num;
*num += 10; // Increment the caller argument
// - confidently
return *num; // Return the incremented value
}
The output from this example is:
Address passed = 0012FF6C
Address received = 0012FF6C
incr10(pnum) = 13
num = 13
The address values produced by your computer may be different from those shown here, but the two values should be identical.
How It Works
In this example, the principal alterations from the previous version relate to passing a pointer, pnum, in place of the original variable, num. The prototype for the function now has the parameter type specified as a pointer to int, and the main() function has the pointer pnum declared and initialized with the address of num. The function main(), and the function incr10(), output the address sent andthe address received, respectively, to verify that the same address is indeed being used in both places. Because the incr10() function is writing to cout, you now call it before the output statement and store the return value in result:
int result {incr10(pnum)};
cout << endl << "incr10(pnum) = " << result;
This ensures proper sequencing of the output. The output shows that this time, the variable num has been incremented and has a value that’s now identical to that returned by the function.
In the rewritten version of incr10(), both the statement incrementing the value passed to the function and the return statement now de-reference the pointer to use the value stored.