What is a simple assertion in C language?

An assertion is a statement which is used to declare positively that a fact must be true when that line of code is reached.

Assertions are useful for obtaining the expected conditions which are met.

Simple Assertion

Simple assertion can be implemented by using assert (expression) method, which is present in assert.h header file.

The syntax for simple assertion is as follows −


In simple assertion,

  • When the condition passed to an assertion which is a true, then, there is no action.
  • The behaviour on false statements depends completely on compiler flags.
  • When assertions are enabled, a false input causes a program to halt.
  • When assertions are disabled, then, there is no action.

Assertions are used only to catch the internal programming errors. These errors occur by passing the bad parameters.


Following is the C program for simple assertion in C programming language −

 Live Demo

#include <stdio.h>
#include <assert.h>
int main(void){
   int x;
   printf("Enter the value of x:
");    scanf("%d",&x);    assert(x >= 0);    printf("x = %d
", x);    return 0; }


When the above program is executed, it produces the following output −

Run 1:
Enter the value of x:
x = 20
Run 2:
Enter the value of x:
Assertion failed!
Program: G:\CP\CP programs\test.exe
File: G:\CP\CP programs\test.c, Line 10
Expression: x >= 0