Unlock access to all the studying documents.
View Full Document
1
This is the first of several lectures which accompany the textbook
Data
Structures and Other Objects Using C++.
Each lecture chooses one
❐An important topic:
Preconditions and Postconditions
2
Throughout the book, preconditions and postconditions are used to
Preconditions and Postconditions
Frequently a programmer must communicate
Can you think of a situationCan you think of a situation
where this would occur ?where this would occur ?
3
As an example, suppose that you are the head of a programming team.
Your team is writing a large piece of software, perhaps with millions of
Example
❐You are the head of a
programming team
HERE ARE
THE REQUIREMENTS
FOR A FUNCTION THAT I
WANT YOU TO
4
There are many ways to specify the requirements for a function. In this
class, and in the textbook, we will use a pair of statements for each
What are Preconditions and
Postconditions?
❐One way to specify such requirements is
with a pair of statements about the function.
5
This is an example of a small function which simply writes the square
root of a number. The number is given as a parameter to the function,
called x. For example, if we call write_sqrt(9), then we would expect
the function to print 3 (which is the square root of 9).
Example
void write_sqrt( double x)
…
6
Example
void write_sqrt( double x)
7
Here again you see the precondition of the example. The right way to
Example
void write_sqrt( double x)
}
8
So, here are three possible function calls. Two of the calls meet the
Example
Which of these function callsWhich of these function calls
meet the precondition ?meet the precondition ?
9
The second and third function calls are fine. The second call has an
Example
Which of these function callsWhich of these function calls
meet the precondition ?meet the precondition ?
10
But the first function call causes trouble. This function call, which
Example
Which of these function callsWhich of these function calls
meet the precondition ?meet the precondition ?
write_sqrt( -10 );
11
Before we continue, take one more quick look at the postcondition: As
Example
void write_sqrt( double x)
12
Here’s one more example, which demonstrates how you can use
ordinary English to express the precondition and postcondition.
The writing of these expressions should be clear and concise. The goal
is to communicate to another programmer two things:
In this example, the “work accomplished” is nothing more than
Another Example
bool is_vowel( char letter )
// Precondition: letter is an uppercase or
…
13
Another Example
What values will be returnedWhat values will be returned
by these function calls ?by these function calls ?