Never confuse education with intelligence, you can have a PhD and still be an idiot.
- Richard Feynman -

Assert in C

From Juneday education
Jump to: navigation, search

In our books we use assertions when writing test code to verify that some other piece of code works.

Let's start with some code. One simple example, not using asserts, if we want to verify that a function (method) calculating the maximum value of two integers passed as parameters.

  printf ("Test max using if statement:");
  value = max(13,14);
  if (value!=14)
      printf (" FAILED\n");
      fprintf(stderr, "max(13,14) failed)");
      fprintf(stderr, "  result   %d\n", value);
      fprintf(stderr, "  expected %d\n", 14);
      /* typically return an error, exit .... */
  printf (" OK\n");

Writing many tests like this soon becomes troublesome. We could write our own test functionality, but we suggest you either use asserts or a unit test framework (such as JUnit och CUnit). If we were to write the above

  printf ("Test max using assert:      ");
  assert (max(13,14)==14);
  printf (" OK\n");

Complete source code for this example: assert-example.c

So, what is an assert then? It's a statement that we want to always be true. Let's go back to the example above and think about max(13,14). We always want that piece of code to be true. So we can "assert" that. If the statement is not true, then the assert fails and typically the program crashes. We typically use asserts, in this book, when writing test code for a function.

And if the assert fails, how do we see that. Let's write an assert we know will fail. Writing the code below is only useful when wanting to show what's printed on a failed assert:

  printf ("Make assert fail:          ");
  assert (max(13,14)==1);
  printf (" OK\n");

Compiling and running this will produce this:

assert-example: assert-example.c:36: main: Assertion `max(13,14)==1' failed.
Make assert fail:          Aborted (core dumped)

the program crashes and we see the cause (file and line number). We rather want a crashing test program than a strange bug at out customer so asserts, or other tests, are our friends.