assert.h

十年热恋 提交于 2020-01-19 03:23:21

ssert.h 定义一个可用作标准调试工具的宏函数(Macro functions):

void assert (int expression);

evaluate assertion

如果具有功能形式的此宏的参数表达式比较等于零(即,表达式为false),则会将一条消息写入标准错误设备,并且中止被调用,终止程序执行。

显示的消息的详细信息取决于特定的库实现,但是它至少应包括:断言失败的表达式,源文件的名称以及发生该消息的行号。常用的表达式格式是:
如果在包含

Assertion failed: expression, file filename, line line number

<assert.h>,名称为的宏 NDEBUG已经定义。这允许编码器包含尽可能多的断言
在调试程序时根据需要在源代码中进行调用,然后通过简单地添加如下行将其全部禁用以用于生产版本:
#define NDEBUG

在代码的开头,在包含之前 <assert.h>。

因此,此宏旨在捕获编程错误,而不是用户或运行时错误,因为通常在程序退出调试阶段后将其禁用。

参数(Parameters)

void assert (int expression);

expression:要评估的表达式。如果该表达式的计算结果为0,则将导致断言失败,该错误将终止程序。

返回值(Return Value)none
Example

/* assert example */
#include <stdio.h>      /* printf */
#include <assert.h>     /* assert */

void print_number(int* myInt) {
  assert (myInt!=NULL);
  printf ("%d\n",*myInt);
}

int main ()
{
  int a=10;
  int * b = NULL;
  int * c = NULL;

  b=&a;

  print_number (b);
  print_number (c);

  return 0;
}

输出:


> 10 Assertion failed: myInt != NULL, file
> C:\Users\asus\source\repos\ConsoleApplication37\ConsoleApplication37\ConsoleApplication37.cpp,
> line 6

参考文档:C标准库官方文档

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!