首页 > 文章列表 > 在C语言中,什么是简单断言?

在C语言中,什么是简单断言?

c语言 简单断言: 断言(assert) 简单断言
328 2023-08-19

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)

在简单的断言中,

  • 当传递给断言的条件为真时,没有任何动作。
  • 对于错误的语句,行为完全取决于编译器标志。
  • 当启用断言时,错误的输入会导致程序停止。
  • 当禁用断言时,没有任何动作。

断言仅用于捕获内部编程错误。这些错误是通过传递错误参数而发生的。

示例

以下是C编程语言中简单断言的示例程序:

 在线演示

#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; }

输出

当上述程序被执行时,它产生以下输出 −

Run 1:
Enter the value of x:
20
x = 20
Run 2:
Enter the value of x:
-3
Assertion failed!
Program: G:CPCP programstest.exe
File: G:CPCP programstest.c, Line 10
Expression: x >= 0