断言 ()- 验证条件

格式

#include <assert.h>
void assert(int expression);

语言级别

ANSI

线程安全

False

描述

如果 expression 为 false (零) ,那么 assert() 函数会将诊断消息打印到 stderr 并异常中止程序。 根据编译期间使用的语言级别,诊断消息具有下列其中一种格式:
Assertion failed: expression, file filename, line line-number.
Assertion failed: expression, file filename, line line-number, function function-name.

如果 expression 为 true (非零) ,那么 assert() 函数不执行任何操作。

使用 assert() 函数可识别程序逻辑错误。 选择 表达式 ,仅当程序按您的期望运行时才保留为 true。 调试程序后,可以使用特殊的无调试标识 NDEBUG 从程序中除去 assert() 调用。 如果使用 #define 伪指令将 NDEBUG 定义为任何值,那么 C 预处理器将展开对 void 表达式的所有断言调用。 如果使用 NDEBUG ,那么必须先定义 NDEBUG ,然后才能将 <assert.h> 包括在程序中。

返回值

没有返回值。
注: assert() 函数定义为宏。 请勿将 #undef 伪指令与 assert()配合使用。

示例

在此示例中, assert() 函数会测试 string 以查找空字符串和空字符串,并在处理这些自变量之前验证 length 是否为正数。
#include <stdio.h>
#include <assert.h>
 
void analyze (char *, int);
 
int main(void)
{
   char *string = "ABC";
   int length = 3;
 
   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);
}
 
void analyze(char *string, int length)
{
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */
}
 
/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3
*****************************************************************/

相关信息