Home  >  Article  >  Backend Development  >  In C language, what is a simple assertion?

In C language, what is a simple assertion?

WBOY
WBOYforward
2023-09-16 17:33:031171browse

In C language, what is a simple assertion?

An assertion is a statement used to affirmatively state that a fact must be true when that line of code is reached.

Assertions are useful for obtaining expected conditions that are met.

>

Simple assertion

Simple assertion can be implemented through the assert(expression) method, which is located in the assert.h header file.

The syntax of a simple assertion is as follows -

assert(expression)

In a simple assertion,

  • No action is taken when the condition passed to the assertion is true.
  • For erroneous statements, behavior depends entirely on compiler flags.
  • When assertions are enabled, incorrect input will cause the program to stop.
  • When assertions are disabled, nothing happens.

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

Example

The following is a sample program for simple assertions in the C programming language:

Online demonstration

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

Output

When the above program When 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

The above is the detailed content of In C language, what is a simple assertion?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete