The Assert Library

I l @ ve RuBoard

The Assert Library

The assert library, supported by the assert.h header file, is a small one designed to help with debugging programs. It consists of a macro named assert() . It takes as its argument an integer expression. If the expression evaluates as false ( non-zero ), the assert() macro writes an error message to the standard error stream ( stderr ) and calls the abort() function, which terminates the program. (The abort() function is prototyped in the stdlib.h header file.) The idea is to identify critical locations in a program where certain conditions should be true and to use the assert() statement to terminate the program if the condition is not true. Typically, the argument is a relational or logical expression. If assert() does abort the program, it first displays the test that failed, the name of the file containing the test, and a line number. Listing 16.14 shows a short example. It asserts that z is greater than or equal to before attempting to take its square root. It also mistakenly subtracts a value instead of adding it, making it possible for z to obtain forbidden values.

Listing 16.14 The checking.c program.
 /* checking.c -- use assert() */ #include <stdio.h> #include <math.h> #include <assert.h> int main() {     double x, y, z;     puts("Enter a pair of numbers (0 0 to quit): ");     while (scanf("%lf%lf", &x, &y) == 2                 && (x != 0  y != 0))     {         z = x * x - y * y;  /* should be + */         assert(z >= 0);         printf("answer is %f\n", sqrt(z));         puts("Next pair of numbers: ");     }     return 0; } 

Here is a sample run:

 Enter a pair of numbers (0 0 to quit):  4 3  answer is 2.645751 Next pair of numbers:  5 3  answer is 4.000000 Next pair of numbers:  3 5  Assertion failed: z >= 0, file C:\checking.c, line 13 

One potentially confusing point to note is that the message is not saying that z >= 0 ; instead, it's saying that the claim z >= 0 failed.

You could accomplish something similar with an if statement:

 if (z < 0) {     puts("z less than 0");     abort(); } 

The assert() approach has several advantages, however. It identifies the file automatically. It identifies the line number where the problem occurs automatically. Finally, there's a mechanism for turning the assert() macro on and off without changing code. If you think you've eliminated the program bugs , place the macro definition

 #define NDEBUG 

before the location where assert.h is included and then recompile the program, and the compiler will deactivate all assert() statements in the file. If problems pop up again, you can remove the #define directive, and recompile, thus reactivating all the assert() statements.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net