C assert()

The void assert() is not a function it is a macro provided by C standard library. It helps to add diagnostics to our C program.The assert() will print a diagnostic message if the assumptions made by the program is false.

void assert(int expression); #where expression can be a variable or any C expression

assert() Parameters:

The assert()  takes an integer type argument. If the expression results in TRUE, assert() does nothing. If the expression results in FALSE then it displays an error message on stderr and the   program execution       is aborted. 

Parameter Description Required / Optional
expression   a variable or any C expression Required

assert() Return Value

This macro does not return any value.

Examples of assert() 

Example 1: How assert() macro works in C?

#include <assert.h>
#include <stdio.h>
int main () {
   int x;
   char string[50];
   printf("Please enter an integer value: ");
   scanf("%d", &x);
   assert(x >= 10);
   printf("Entered integer value is %d\n", x);
   printf("Please enter a string: ");
   scanf("%s", string);
   assert(string != NULL);
   printf("Entered string is: %s\n", string);


Please enter an integer value: 5
Entered integer value is 5
Please enter a string: Programming
Entered string is: Programming 

Example 2: Working of assert() in C program.

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

int main(int argc, const char * argv[])
    int expres = 1;
    printf("Expression is %d\n", expres);

    /* Assert should not exit in this case since exp is not 0  */
    expres= 0;
    printf("Expression is %d\n", expres);
    return 0;


Expression is 1
Expression is 0
assert: assert.c:24: main: Assertion `expres' failed.
Aborted (core dumped)