In this section we will consider how to formalize theories on the correct "state" of a program, and use that information for active testing within the code.
Later we will also consider the exception-handling aspect of program reliability.
cassert
library
provides a special testing feature, called the assert
function
assert
is used to double-check conditions you're certain
must be true
Example: a square root routine might assume it is never called with a negative value:
double squareroot(double x) { // test for negative values of x assert(x >= 0.0); // now continue with regular code ... }Assert tests the listed condition, and if it evaluates to false assert terminates the program with an error message (the message usually indicates which assert statement caused termination)
The drawback is that the use of assertions does slow down the execution speed of the program. In practice, assertions are usually used during until program testing and debugging is complete. Appropriate corrections and error handling are added to the software to ensure correct behaviour, and after testing is completed the assertions are turned off.
Some examples might include:
assert(den != 0); x = num / den;
assert(age >= 0); cout << "The age of the car is " << age << " years";
assert((index >= 0) && (index < ARRSIZE)); cout << myarray[index] << endl;
assert(y != 0); for (x = 0; x < M; x = x + y) { // body of loop }
for (...) { sum = ... } assert(sum >= 0);
assert(x >= 0); y = sqrt(x);
// create a backup copy of a string strcpy(backup, mystring); // call foo to do something based on mystring foo(mystring); // check that foo didn't change string assert(strcmp(backup, mystring) == 0);
To turn off assertions, the easiest approach is to add the following line of code above the #include <assert> statement:
// automatically disable assertion checking #define NDEBUG #include <cassert>To turn assertion checking back on (for example if testing a modification to the program) you can simply remove that line again.