You are here

assert in C

Assert is a macro which is used to check specific conditions at runtime (when the program is under execution) and is very useful while debugging a program. To use it you must include the header file "assert.h" in your program.

Declaration: void assert(int expression);

An expression is any valid C language expression, most of the times it's a condition. In the program, we divide two integers or calculate a/b (where a and b are integers), and you know that b can't be zero, so we use, assert(b != 0) in our program. If this condition (b != 0) holds true, then the program execution will continue. Otherwise, it terminates, and an error message is displayed on the screen displaying filename, line number, function name, the condition which does not hold true (see image below).

C programming code

  1. #include <stdio.h>
  2. #include <assert.h>
  4. int main() {
  5.   int a, b;
  7.   printf("Input two integers to divide\n");
  8.   scanf("%d%d", &a, &b);
  10.   assert(b != 0);
  12.   printf("%d/%d = %.2f\n", a, b, a/(float)b);
  14.   return 0;
  15. }