UMBC CS 201, Fall 02
UMBC CMSC 201 Fall '02 CSEE | 201 | 201 F'02 | lectures | news | help

Assert() statements

Assert() statements can help you narrow down where your problems are happening. An assert() statement contains a condition as a parameter. If the condition is false, assert() prints out a helpful message telling you what file and what line number is causing the problem, and then quits your program. For example, the code int StartSocialSecurity(int age, int ssn) { assert( age == 65 ); . . . } will produce the error message: Assertion failed: age == 65, file security.c, line xx if, at that point in your code, the variable age wasn't 65.

Here's an example of using assert() :

/* assert.c: This program demonstrates * the use of the assert() utility */ #include <assert.h> #include <stdio.h> main() { int i, num_lines = 0; /* Count to 100 by 2's */ for(i = 0; i != 100; i += 2) { /* print a pattern*/ printf("~\\/~\\/"); if(i % 15 == 0) { printf("~\n"); /* count the number of lines*/ i++; } /* something's wrong: make sure */ /* it's doing what I think it is */ assert(i < 101); } return 0; }

Output:

linux3[83] % a.out ~\/~\/~ ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~ ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~ ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~ ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~ ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~ ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/~ a.out: sample.c:24: main: Assertion `i < 101' failed. ~\/~\/~\/~\/~\/~\/~\/~\/~\/~\/Abort linux3[84] % Assert statements should never be left in code. They should only be used for debugging. There are much more graceful ways to exit a program than this.


CSEE | 201 | 201 F'02 | lectures | news | help

Monday, 11-Nov-2002 17:40:24 EST