Home > Backend Development > C++ > body text

In C language, what is a simple assertion?

WBOY
Release: 2023-09-16 17:33:03
forward
1238 people have browsed it

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)
Copy after login

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;
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template