What is a simple assertion in C language?

CServer Side ProgrammingProgramming

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 −

assert(expression)

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.

Example

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:\n");
   scanf("%d",&x);
   assert(x >= 0);
   printf("x = %d\n", x);
   return 0;
}

Output

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

Run 1:
Enter the value of x:
20
x = 20
Run 2:
Enter the value of x:
-3
Assertion failed!
Program: G:\CP\CP programs\test.exe
File: G:\CP\CP programs\test.c, Line 10
Expression: x >= 0
raja
Published on 26-Mar-2021 12:16:52
Advertisements