Page last updated 04/21/99
C++ has many functions available
sqrt pow string::length ostream::width
Functions are more easily understood when documented with comments see next slide
Preconditions and postconditions are C++ comments that represents a contract between the implementers of a function and the user (client) of that function.
double sqrt(double x) // pre: x >= 0 // post: Returns square root of x
A function heading is the complete declaration of a function without its implementation (body)
The heading is sometimes called the function's signature.
For example, this signature tells us how to call the function (number of parameters and
type of parameters), but not how it works:
double sqrt(double x)
General form of a function heading:
return-type function-name ( parameter-list )
General form for declaring parameters:
class-name identifier class-name & identifier
double f(double x) void init(grid& g)
int max(int j, int k) int roots(double a,
double b, double c,
double& r1, double& r2)
double f(double x, double y) // post: return x-y;
cout << f(3.0, -5.32);
x = 3.0;
y = -5.32;
Write the output generated by these function calls:
cout << f( 1.0, 1.0) << endl; // _____
cout << f( 1.0, 1.5) << endl; // _____
cout << f( 3.0, 0.5) << endl; // _____
cout << f(-1.0, 1.0) << endl; // _____
Write valid for each valid function call or explain why the code is incorrect?
f(1.0) |
f("Bob", "Sue")
|
f(-0.001, +4.5) |
f(1, 2) |
f(1, 2, 3) |
f((1, 2) |
Given the following function heading :
double larger(double a, double b) // post: return the larger of a and b
What type (class) of value is returned when larger is called _______ ?
What is the function name _______ ?
How many arguments are required to call the function ___________ ?
What class of arguments are required in the function call __________ ?
Given the following function heading :
double foo(double a, double b) // pre: a is not equal to b // post: Return the lesser of a and b
write the return value of these function calls: foo( 3.0, 6.0) ________ foo( 6.0, 3.0) ________ foo(-3.0, -6.0) ________ foo(-3.0, -3.0) ________
Documented function headings provide the following information: