什么是“断言"?功能? [英] What is the "assert" function?

查看:34
本文介绍了什么是“断言"?功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习 OpenCV 教程并遇到了 assert 函数;它有什么作用?

I've been studying OpenCV tutorials and came across the assert function; what does it do?

推荐答案

assert 将终止程序(通常带有引用 assert 语句的消息)如果它的参数结果为假.常用于调试时,使程序在出现意外情况时更明显地失败.

assert will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.

例如:

assert(length >= 0);  // die if length is negative.

如果失败,您还可以添加信息更丰富的消息,如下所示:

You can also add a more informative message to be displayed if it fails like so:

assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");

或者像这样:

assert(("Length can't possibly be negative! Tell jsmith", length >= 0));

当您进行发布(非调试)构建时,您还可以通过定义 NDEBUG 宏来消除评估 assert 语句的开销,通常带有编译器开关.其推论是您的程序应该永远依赖于 assert 宏的运行.

When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assert statements by defining the NDEBUG macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.

// BAD
assert(x++);

// GOOD
assert(x);    
x++;

// Watch out! Depends on the function:
assert(foo());

// Here's a safer way:
int ret = foo();
assert(ret);

从程序调用 abort() 和不能保证做任何事情的组合来看,断言应该只用于测试开发人员已经假设的事情,而不是,例如,用户输入一个数字而不是一个字母(应该通过其他方式处理).

From the combination of the program calling abort() and not being guaranteed to do anything, asserts should only be used to test things that the developer has assumed rather than, for example, the user entering a number rather than a letter (which should be handled by other means).

这篇关于什么是“断言"?功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆