PHYCS 3730/6720 Lab Exercise

Reading and references: This exercise provides more practice with pointers and introduces references. We start with the files of ~p6720/exercises/refs_functions. Please copy them to a working directory.

The answer file for this exercise is lab08.


Exercise 1. References as function arguments

Look at the functions call_f.cc and f.cc. Compile call_f and run it. To compile and link from two source files, just tell g++ the names of both source files:

   g++ call_f.cc f.cc -o call_f
or, better still, use the Makefile with make call_f. Then answer these questions in the answer file:

Exercise 2. Practice with reference syntax

Modify the code in the previous example so y is passed as a reference, rather than a pointer.

Hint: Be sure you change the main program and subprogram everywhere you see f and the subprogram everywhere you see y_ptr.

Copy your modified code to the answer file.


Exercise 3. Can output arguments be passed as values?

See what happens if you try passing the argument for the output dydx by value (as we do x). Start from the original code in ~p6720/exercises/refs_functions. Modify the code so dydx is passed to the function f by value instead of by reference. Then compile and run it.

Hint: Be sure you change the main program and subprogram everywhere you see f and the subprogram everywhere you see y_ptr.

Second Hint: If you are still stuck, here is what you do. In the declaration for the function f in call_f.cc, change double & to double. That makes the argument a value instead of a reference. Do the same thing in the file f.cc.

In your answer file, say what changed in your result when you did this.


Exercise 4. Single file compilation

Returning to the original code in ~p6720/exercises/refs_functions, what happens if you remove the function prototype declaration from the main program? Try it by compiling it that way. Say what happened in your answer file.

Combine both program files into a single file as follows. Replace the prototype declaration from the main program with the five-line function definition from the file f.cc (lines from void f... through the close curly brace}). Try recompiling just the file call_f.cc and running it. Does this work?

Putting either the full function definition or the prototype at the top of the code defines f for the rest of the file.