What We Will Cover
Continuations
Homework Questions?
- A4: Tally Ho! (9/30/04)
Exercise 4 and CodeLab Lesson 4 (9/30/04)
Questions from last class?
What is output by the following program? (Do not run the code -- work it out by hand)
#include <iostream>
using namespace std;
int mystery(int param);
int main() {
int num = 2;
cout << "At first, num=" << num << endl;
num = mystery(num);
cout << "Later, num=" << num << endl;
return 0;
}
int mystery(int param) {
cout << "param=" << param << endl;
param = param * 2;
return param;
}
-
At first, num=2
Later, num=2
-
At first, num=2
param=2
Later, num=2
-
At first, num=2
param=2
Later, num=4
- None of these
^ top
6.1: Developing, Testing and Debugging Functions
Objectives
At the end of the lesson the student will be able to:
- Describe how to design functions
- Code driver functions
- Code stub functions
|
^ top
6.1.1: Designing Functions
- Functions are subprograms whose purpose is to transform data
- As subprograms, they usually receive inputs and produce outputs

- Examples of functions include:
- Converting keyboard entries into letters and numbers
- Changing ounces to millimeters
- Converting data into a report displayed on the screen
Function Content
- A function is like a paragraph in a writing
- Each paragraph should discuss one topic
- Similarly, each function should do only one thing and do it well
- The function's name should describe that action
- You should try to develop one function for each conceptual activity in your program
- All the statements in a function should focus on doing that one thing
Input and Output
- When you organize your code into functions, you want them to be as independent from one another as possible
- To create this independence, you control the inputs and outputs
- A function can get input from many sources
- Arguments from the function call
- Constants from outside the function
- Keyboard or another device
- Similarly, a function can express its output many places
- Return a value
- Display information to the screen
- Alter data passed as references (cover later)
- Alter instance variables (cover later)
- Your function should accept input from as few sources as possible
- Also, your function should take as input only data needed by the function
- Output from the function should only be the actual data produced by the function
^ top
6.1.2: Implementing Functions
- Functions should be developed as self-contained modules
- They can be designed and developed separately the from rest of program
- Often, different functions are assigned to different programmers
- All the programmers must understand how the functions are used
- In addition, they must agree on the function interface
Function Interfaces
- Most of the information for a function interface is contained in the header
void performCalcuation(double dataToConvert);
If function and parameter names are chosen well, most programmers will understand the purpose of the function
^ top
6.1.3: First Implementation: Stubs
- When you first implement a set of functions, it often makes sense to use stubs
- Stubs are dummy functions that are called instead of the real function
- They usually display a message acknowledging they were called
- Sometimes they provide simple values for testing
- Stubs should be so simple that you have confidence they will perform correctly
For Example
- If a function does not have to return anything, you can code an empty function
void performCalcuation(double dataToConvert) {}
If you want to see when a function is called, add a print statement
void performCalcuation(double dataToConvert) {
cout << "Executing performCalcuation\n";
}
If the function needs to return a value, simply return a known value
double transformValue(double in) {
cout << "Executing transformValue\n";
return 0.0;
}
You can return later and write the complete function
Keep stubs so simple that you are confident they perform correctly
If stubs get too complex, it is better to just write the function
Once the functions are "stubbed out" you should develop a driver for testing
^ top
6.1.4: Drivers and Testing
- Drivers are functions that send test data to all the other functions
- Drivers allow you to test each function in your program
- This enables you to complete each of your functions one at a time
- Drivers should send both correct and incorrect data for testing
- Once a function is tested, it can be used in the driver program to test other functions
For Example
- Following is an example of a main function to drive the tests for the stubs shown above
#include <iostream>
using namespace std;
void performCalcuation(double dataToConvert);
double transformValue(double in);
int main() {
cout << "Calling performCalcuation\n";
performCalcuation(1.0);
cout << "Calling transformValue\n";
double result = transformValue(1.0);
cout << " Result=" << result << endl;;
}
void performCalcuation(double dataToConvert) {
cout << "Executing performCalcuation on "
<< dataToConvert << endl;
}
double transformValue(double in) {
cout << "Executing transformValue on "
<< in << endl;
return 0;
}
Programming Style: Function Length
- Functions that are too long are hard to understand
- Long functions often mean you need to restructure your code into more functions
- As a general rule, functions should be less than what will fit on one screen
^ top
6.1.5: Putting the Pieces Together
- Once your functions work correctly, it is time to assemble the final program
- You replace the driver code following the design of your program algorithm
- Program development is an iterative process
- You often have to make changes to previous code
Debugging the Program
- Lots of output statements to trace the execution
- Once developed, you remove all these statements before submitting
^ top
6.1.6: Summary
- Functions are subprograms whose purpose is to transform data
- Each function should do only one thing and do it well
- To improve flexibility, your function should accept input from as few sources as possible
- As you develop functions, you need to test each one individually
- Drivers are used to test the individual functions
- You should send both correct and incorrect data for testing
- Once a function is tested, it can be used in the driver program to test other functions
- Stubs are dummy functions that are called instead of the real function
- They usually display a message acknowledging they were called
- Sometimes they provide simple values for testing
- Stubs should be so simple that you have confidence they will perform correctly
- After your function work correctly, you replace the driver with the main program
^ top
Exercise 6.1
- Start a text file named exercise6.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 6.1
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Spend 5 minutes reviewing the specification for the next assignment
We will review the specification and work on the design together during this exercise.
- Record a description of the design in
exercise6.txt.
^ top
6.2: Programming Style Reviewed
Objectives
At the end of the lesson the student will be able to:
- Discuss the purpose of programming style
- Describe the programming style requirements to date
|
^ top
6.2.1: About Programming style
- Programming style is about how you organize and document your code.
- A program is written once, but read many times
- During debugging
- When adding to the program
- When updating the program
- When trying to understand the program
- Anything that makes a program more readable and understandable saves lots of time, even in the short run
- Programs written following a consistent style are:
- Easier to read
- Easier to correct
- Easier to maintain
- We will discuss programming style and these tools in this section
^ top
6.2.2: Programming Style Requirements to Date
- Below is a list of programming style requirements covered so far
- Will have more as the course continues
- Difficult to remember them all
- Can set your text editor to eliminate some problems automatically
Programming Style Topics to Date
- Use block comments at the start of a program (2.1.1)
- Line length (2.1.2)
- Identifiers have naming convention (2.1.3)
- Do not use tabs (2.2.5)
- Spacing required around operators (2.3.5)
- No spacing after opening or before closing parenthesis (2.3.5)
- Variable names have naming convention (2.4.2)
- Constant names have naming convention (2.4.3)
- No "magic" numbers (2.4.3)
- Curly braces in if-else statements (4.2.3)
- Curly braces in while statements (4.3.4)
- Function names (5.4.1)
- Function comment blocks (5.4.1)
- No use of global variables (5.4.6)
^ top
6.2.3: Documenting Your Code
Following is available from the How To Document and Organize C++ Code.
^ top
6.2.4: Summary
- Programming style is about how you organize and document your code.
- Programs written following a consistent style are:
- Easier to read
- Easier to correct
- Easier to maintain
- Programmers use the documentation to understand how to use your code
^ top
Exercise 6.2
- Label this exercise: Exercise 6.2
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise6.txt.
Specifications
- Document the following program following the standards. Save your documented program along with this weeks exercises.
Q1: Why should you document your code following standards?
Q2: What is the purpose of an @param tag?
#include <iostream>
using namespace std;
// Function prototype
long pow(int base, int exponent);
int main() {
long value = pow(2, 3);
cout << value << endl;
return 0;
}
long pow(int base, int exponent) {
if (exponent == 0) {
return 1;
}
int loopCounter = 1;
long result = base;
while (loopCounter < exponent) {
result = result * base;
loopCounter++;
}
return result;
}
^ top
6.3: Call-By-Reference Parameters
Objectives
At the end of the lesson the student will be able to:
- Explain the difference between call-by-value and call-by reference parameter passing
- Return values from functions using call-by-reference
|
^ top
6.3.1: About Parameter Passing
- Two ways to pass arguments to parameters
- Call-by-value
- A copy of the value is passed
- Call-by-reference
- The address of the actual argument is passed
- All our functions so far have used call-by-value parameters
Call-by-Value Parameters
- A copy of the actual argument is passed
- Same as a local variable with special initialization inside the function
- If modified, only the local copy changes
- The function has no access to the actual argument from the caller
- This is the default operation for function calls
- Used in all our examples so far
Example of Call-ByValue Parameters
- What does this program output?
#include <iostream>
using namespace std;
int mystery(int param);
int main() {
int num = 2;
cout << "At first, num=" << num << endl;
num = mystery(num);
cout << "Later, num=" << num << endl;
return 0;
}
int mystery(int param) {
cout << "param=" << param << endl;
param = param * 2;
return param;
}
^ top
6.3.2: Call-By-Reference Parameters
- C++ has another parameter-passing mechanism known as call-by-reference
- Used to provide access to caller's actual argument inside a function
- Caller's data can be modified by the called function!
- Specified by an ampersand '
&' after the type in the parameter list
For Example
- Here is a program that outputs the same things as the previous example
- What is different?
#include <iostream>
using namespace std;
void mystery(int& param);
int main() {
int num = 2;
cout << "At first, num=" << num << endl;
mystery(num);
cout << "Later, num=" << num << endl;
return 0;
}
void mystery(int& param) {
cout << "param=" << param << endl;
param = param * 2;
}
Call-By-Reference Details
- What's really passed in?
- A reference back to the caller's original argument!
- Refers to memory location of the original argument
- Called an address, which is a unique number referring to a place in memory
- Note that arguments for call-by-reference parameters must be variables, not constants
^ top
6.3.3: Mixed Parameter Lists
- You can combine parameter-passing mechanisms
- Parameter lists can include pass-by-value and pass-by-reference parameters
- As usual, the order of arguments in the list is critical:
void mixedCall(int& par1, int par2, double& par3);
Function call:
int arg1 = 0, arg2 = 1;
double arg3 = 2.2;
mixedCall(arg1, arg2, arg3);
arg1 must be integer type and is passed by reference
arg2 must be integer type and is passed by value
arg3 must be double type and is passed by reference
^ top
6.3.4: Summary
- A formal parameter is a local variable with special initialization
- The parameter is filled in with the actual argument during the function call
- Call-by-value parameters are local copies of argument in the function body
- The actual argument cannot be modified
- Call-by-reference parameters allow you to change the variable used in the function call
- Actual argument can be modified
'&' symbol (ampersand) identifies call-by-reference variables
- Call-by-reference passes the memory address of actual argument
- Whatever is done to a formal parameter in the function body, is actually done to the value at the memory location of the argument variable
- Makes the parameter an alias for the original argument
- Arguments for call-by-reference parameters must be variables, not constants
- You can mix call-by-value and call-by-reference parameters in a function
void mixedCall(int& par1, int par2, double& par3);
^ top
Exercise 6.3
- Label this exercise: Exercise 6.3
- Complete the following and record the answers to any questions in exercise6.txt.
Specifications
Consider the following program:
#include <iostream>
using namespace std;
void swapValues(int& variable1, int& variable2);
int main() {
int num1 = 1, num2 = 2;
cout << "Original values: " << num1 << " " << num2 << endl;
swapValues(num1, num2);
cout << "Swapped values: " << num1 << " " << num2 << endl;
return 0;
}
void swapValues(int& variable1, int& variable2) {
int temp = variable1;
variable1 = variable2;
variable2 = temp;
}
Q1: What does the program do?
Q2: What output do you get if you remove the ampersands '&' from the swapValues() parameter list?
Q3: How do call-by-value and call-by reference differ?
^ top
6.4: Overloading Function Names
Objectives
At the end of the lesson the student will be able to:
- Code overloaded functions
- Describe how C++ resolves function calls
- Describe when to overload functions
|
^ top
6.4.1: About Overloading
- You can have several functions with the same name in a program
- Need different parameter set (i.e. signature) for each function
- Number of parameters
- Parameter types
- Order of parameters
- Return type is not part of the signature
- Cannot be used to distinguish between two functions with the same name and signature
For Example
#include <iostream>
using namespace std;
// Function prototypes
double square(double x);
int square(int x);
int main() {
cout << square(5) << endl;
cout << square(6.5) << endl;
}
int square(int x) {
cout << "Using type int: ";
return x * x;
}
double square(double x) {
cout << "Using type double: ";
return x * x;
}
First call to square uses function with int signature
Second call uses function with double signature
Using type double: 42.25
Using type int: 25
^ top
6.4.2: Overloading Resolution
- Function call resolution:
- Looks for exact signature
- Looks for 'compatible' signature
- First: looks for exact signature
- Because no argument conversion required
- Second: looks for 'compatible' signature
- First where promotion is possible, with no loss of data
int => double
Second with demotion, with a possible loss of data
double => int
For Example
- Given following functions:
void f(int n, double m) {}
void f(double n, int m) {}
void f(int n, int m) {}
- Making these calls:
f(98, 99); => Calls 3
f(5.3, 4); => Calls 2
f(4.3, 5.2); => ??
- Avoid such confusing overloading
^ top
6.4.3: Automatic Type Conversion and Overloading
- Typically you should make numeric formal parameters of type
double
- Allows for any numeric type
- Any narrower data type can safely be promoted to wider types
- Avoids overloading because of different numeric types
For Example
double mpg(double miles, double gallons) {
return (miles / gallons);
}
Example function calls:
mpgComputed = mpg(5, 20);
- Converts
5 and 20 to doubles, then passes them to the function
mpgComputed = mpg(5.8, 20.2);
mpgComputed = mpg(5, 2.4);
- Converts
5 to 5.0, then passes the values to the function
^ top
6.4.4: Default Arguments
- C++ allows functions with default arguments
- If the argument is omitted during the function call, uses default values instead
- Specified in function declaration (prototype)
- Only the rightmost parameters can have default values
void showVolume(int length, int width = 1, int height = 1);
Last 2 arguments have defaults
Possible function calls:
showVolume(2, 4, 6); // all arguments supplied
showVolume(3, 5); // height defaulted to 1
showVolume(7); // width and height defaulted to 1
^ top
6.4.5: Summary
- A programmer can declare many functions using the same name
- However, the parameter list must be different between each function
- Useful when you want to have the same function operate on different data types
- However, you can avoid overloading for numbers by relying on automatic type conversion
- C++ automatically changes values to the needed type
- By making your numeric types
double, you can use promotion instead of overloading
- Also, you can make function calls using default arguments
^ top
Exercise 6.4
- Label this exercise: Exercise 6.4
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise6.txt.
Specifications
- Suppose you have two functions:
double score(double time, double distance) {}
double score(double points) {}
Which function would be used in the following function call?
double finalScore = score(95.7);
- Suppose you have two functions:
double answer(double data1, double data2) {}
double answer(double time, int count) {}
Which function would be used in the following function call?
double y = 5.0;
double x = answer(y, 6.0);
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: November 22 2004 @14:21:39
|