assert在C++中的应用

本文深入探讨了C++中assert宏的用法,包括其工作机制、参数、返回值及常见应用场景。通过实例展示了如何在代码中使用assert来捕获编程错误,并提供了断言宏的配置方法以适应不同开发阶段的需求。
void assert (int expression);

Evaluate assertion

If the argument expression of this macro with functional form compares equal to zero (i.e., the expression is false), a message is written to the standard error device and abort is called, terminating the program execution.

The specifics of the message shown depend on the specific implementation in the compiler, but it shall include: the expression whose assertion failed, the name of the source file, and the line number where it happened. A usual expression format is:

Assertion failed: expression, file filename, line line number
This macro is disabled if at the moment of including assert.h a macro with the name NDEBUG has already been defined. This allows for a coder to include many assert calls in a source code while debugging the program and then disable all of them for the production version by simply including a line like:
#define NDEBUG at the beginning of its code, before the inclusion of assert.h.

Therefore, this macro is designed to capture programming errors, not user or running errors, since it is generally disabled after a program exits its debugging phase.

Parameters

expression
Expression to be evaluated. If this expression evaluates to 0, this causes an assertion failure that terminates the program.

Return Value

none

Example

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

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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值