CS120
Lab #5
Due at the end of lab.
For this lab you will be experimenting with functions that use 'pass-by-value' and
'pass-by-reference' for their arguments. There are four questions as part of the
lab, and you will need to turn in your (short) answers to these questions.
- So far we have been using pass-by-value arguments, in which a value is passed to
a function as an argument. Consider the following code:
int x = 7;
int y = 20;
flip(x, y); // this is a function call
cout << x << " " << y << endl; // should print 20 7
Question 1) Could you write the code for the definition of the flip() function so
that the values of x and y are switched? (so that x becomes 20 and y becomes 7.) Why or why
not?
- Try compiling and running this test program code.
Look carefully at the output and the code.
Question 2) What do you notice about how the value of x changes after function1() is called?
Question 3) What do you notice about how the value of x changes after function2() is called?
Question 4) What is the difference in code between function1() and function2() besides the name of the functions?
- The & makes a function use 'pass-by-reference' instead of 'pass-by-value'.
Pass-by-reference means that a reference to the variable - literally the
variable's location (address)
in memory - is passed to the function. Because the function knows the location of the
variable in memory, when it makes a change to the variable that change affects
the original variable's value as well.
- Using your new knowledge of pass-by-reference arguments, create the flip() function described in the first part of the lab using pass-by-reference. Your flip() function must take two arguments and switch the values associated with the two arguments. Write a main() function to demonstrate that the flip() function works.
Turn in: Use the script command to demonstrate how your program runs.
Place the output from the script command in a file named Lab5output.txt.
Add your answers to the four questions above to the script file, then turn in a copy of your program code and your Lab5output.txt file to Canvas.