Assert()-有什么用? [英] Assert() - what is it good for ?

查看:175
本文介绍了Assert()-有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白assert()的目的.

我的讲师说,assert的目的是发现错误.

My lecturer says that the purpose of assert is to find bugs .

例如:

double divide(int a , int b ) 
{
  assert (0 != b);
  return a/b;
}

以上断言是否合理?我认为答案是肯定的,因为如果我的程序 不能与0(数字零)一起使用,但是以某种方式零确实会进入b变量,那么代码出了点问题.

Does the above assert justified ? I think that the answer is yes , because if my program doesn't supposed to work with 0 (the number zero) , but somehow a zero does find its way into the b variable , then something is wrong with the code .

我正确吗?

您能告诉我一些合理 assert()的示例吗?

Can you show me some examples for a justified assert() ?

致谢

推荐答案

assert用于验证如果 程序是正确的.在您的示例中assert是否合理 取决于divide的规范:如果b != 0是前提, 那么assert通常是验证它的首选方法: 有人在不满足前提条件的情况下调用该函数,这是一个 编程错误,您应该以极端的方式终止程序 偏见,尽量少做额外的工作. (通常. 在某些情况下,有些情况并非如此,在某些情况下 最好抛出一个异常,然后偶然发现,寻求最好的结果.) 但是,如果divide的规范定义了b == 0时的somw行为(例如,返回+/- Inf),那么您应该实现它而不是 使用断言.

assert is used to validate things that should always be true if the program is correct. Whether assert is justified in your example depends on the specification of divide: if b != 0 is a precondition, then the assert is usually the preferred way of verifying it: if someone calls the function without fulfilling the preconditions, it is a programming error, and you should terminate the program with extreme prejudice, doing as little additional work as possible. (Usually. There are applications where this is not the case, and where it is better to throw an exception, and stumble along, hoping for the best.) If, however, the specification of divide defines somw behavior when b == 0 (e.g. return +/-Inf), then you should implement this instead of using assert.

此外,如果事实证明assert也可以关闭 需要太多的运行时间.但是,通常,仅应在 关键的代码部分,并且仅在探查器显示您 真的需要它.

Also, it's possible to turn the assert off, if it turns out that it takes too much runtime. Generally, however, this should only be done in critical sections of code, and only if the profiler shows that you really need it.

FWIW:与您的问题无关,但是您发布的代码将 为divide( 1, 3 )返回0.0.不知何故,我不认为这是 你想要什么.

FWIW: not related to your question, but the code you've posted will return 0.0 for divide( 1, 3 ). Somehow, I don't think that this is what you wanted.

这篇关于Assert()-有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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