assert : <assert.h> library function

The assert C Library macro void assert(int expression); allows diagnostic information to be written to the standard error file. If the result of argument expression equal to false( which is equal to zero), a message is written to the standard error device and abort function is called which in turn terminates the program.
If expression evaluates to TRUE(non zero value), assert does nothing.

This macro will get disabled, if we define a macro with the name NDEBUG before including assert.h in program.

#define NDEBUG
This allows us to put debug statements during development phase and blocking all assert statement after development by defining NDEBUG macro.

Function prototype of assert

void assert(int expression);
  • expression : This is the expression to be evaluated. If this expression evaluates to 0, this causes an assertion failure and termination of program.

Return value of assert

NONE

C program to show the use of assert function

The following program shows the use of assert macro to print error message before program termination.

#include <stdio.h> 
#include <assert.h>

int main(){
   int numerator, denominator;
   float quotient;
  
   printf("Enter numerator and denominator\n");
   scanf("%d %d", &numerator, &denominator);
   
   assert(denominator != 0);
   quotient = (float)numerator/denominator;
   printf("Quotient of %d/%d is %f\n", numerator, 
       denominator, quotient);

   return(0);
}


Program Output
Enter numerator and denominator
7 4
Quotient of 7/4 is 1.750000
Enter numerator and denominator
7 0
Assertion failed: denominator != 0, file C:\Programs\assert.c, line 11