Site Sections => About Us | Consultancy | Training | Software | Publications | Open Source | Support | Open Standards | FAQ | Jobs
Site Style Info

9.2. Diagnostics

While you are debugging programs, it is often useful to check that the value of an expression is the one that you expected. The assert function provides such a diagnostic aid.

In order to use assert you must first include the header file <assert.h>. The function is defined as

#include <assert.h>

void assert(int expression)

If the expression evaluates to zero (i.e. false) then assert will write a message about the failing expression, including the name of the source file, the line at which the assertion was made and the expression itself. After this, the abort function is called, which will halt the program.

assert(1 == 2);

/* Might result in */

Assertion failed: 1 == 2, file silly.c, line 15

Assert is actually defined as a macro, not as a real function. In order to disable assertions when a program is found to work satisfactorily, defining the name NDEBUG before including <assert.h> will disable assertions totally. You should beware of side effects that the expression may have: when assertions are turned off with NDEBUG, the expression is not evaluated. Thus the following example will behave unexpectedly when debugging is turned off with the #define NDEBUG.

#define NDEBUG
#include <assert.h>

void
func(void)
{
        int c;
        assert((c = getchar()) != EOF);
        putchar(c);
}
Example 9.2

Note that assert returns no value.

The C Book

This book is published as a matter of historical interest. Please read the copyright and disclaimer information.

GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested.


West Yorkshire Office

GBdirect Ltd
Bradford Design Exchange
34 Peckover Street
BRADFORD
BD1 5BD
West Yorkshire
United Kingdom

consulting@gbdirect.co.uk

Training: 0800 651 0338
General: +44 (0)870 200 7273
Finance: +44 (0)1353 615 174

Please call between 0900 and 1700 (UK time) on Monday to Friday


South East Regional Office

GBdirect Ltd
18 Lynn Rd
ELY
CB6 1DA
Cambridgeshire
United Kingdom

consulting@gbdirect.co.uk

Training: 0800 651 0338
General: +44 (0)870 200 7273
Finance: +44 (0)1353 615 174

Please call between 0900 and 1700 (UK time) on Monday to Friday


Please note:
Non-training enquiries should be directed, initially, to our UK national office in Bradford (West Yorkshire), even if the enquiry concerns services delivered in London or South/East England. Clients in London and the South East will typically be handled by staff working in the London or Cambridge areas.