UMBC CMSC 201 Spring '05 CSEE | 201 | 201 S'05 | lectures | news | resources |discussion| help

Assert

Assert() statements

Assert() statements can help you narrow down where your problems are happening.

An assert statment like assert(x>0) asserts a condition that should be true of you program was written correctly, i.e. bug free.

  • Note that the assert statement takes a condition as a parameter.
  • If the contion is true, assert does nothing
  • If the condition is false, 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 a complete 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] % 

Turning off Assert()

Assertions are for debugging and should not be left enabled in a program after debugging.

  • They slow the program down
  • More importantly, they ungracefully terminate the program -- you don't want your user to experience this.

There are two ways to do this

  1. Delete them from, or comment them out of, your program
  2. Add #define NDEBUG 1 after #include <assert.h>


CSEE | 201 | 201 S'05 | lectures | news | resources | help |

Monday, 18-Apr-2005 13:44:19 EDT