Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (595.53 KB, 10 trang )
<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>
An important topic:
An important topic:
preconditions
preconditions and and
postconditions
postconditions..
They are a method of
They are a method of
specifying what a
specifying what a
function accomplishes.
function accomplishes.
Data Structures
Data Structures
and Other Objects
and Other Objects
Using C++
Frequently a programmer must communicate
Frequently a programmer must communicate
precisely
precisely what<sub>what</sub> a function accomplishes, a function accomplishes,
without any indication of
without any indication of <sub>how</sub><sub>how</sub> the function <sub> the function </sub>
does its work.
does its work.
One way to specify such requirements is
One way to specify such requirements is
with a pair of statements about the function.
with a pair of statements about the function.
The
The <sub>precondition</sub><sub>precondition</sub> statement indicates what <sub> statement indicates what </sub>
must be true before the function is called.
must be true before the function is called.
The
The <sub>postcondition</sub><sub>postcondition</sub> statement indicates what <sub> statement indicates what </sub>
will be true when the function finishes its
will be true when the function finishes its
work.
void write_sqrt(double x)
// <sub>Precondition: x >= 0.</sub>
// Postcondition: The square root of x has
// <sub>been written to the standard output.</sub>
void write_sqrt( double x)
// Precondition: x >= 0.
// Postcondition: The square root of x has
// been written to the standard output.
}
The precondition and
The precondition and
postcondition appear as
postcondition appear as
comments in your program.
void write_sqrt( double x)
// Precondition: x >= 0.
// Postcondition: The square root of x has
// been written to the standard output.
}
In this example, the precondition
In this example, the precondition
requires that
requires that
x >= 0<b>x >= 0</b>
be true whenever the function is <sub>be true whenever the function is </sub>
called.
write_sqrt( 10 );
write_sqrt( 0 );
write_sqrt( 5.6 );
write_sqrt( 0 );
write_sqrt( 5.6 );
write_sqrt( 10 );
write_sqrt( 0 );
write_sqrt( 5.6 );
But the first call violates the