什么是断言?你为什么要使用它们? [英] What are assertions? and why would you use them?

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

问题描述

如何在c ++中完成断言?示例代码非常感谢。

How are assertions done in c++? Example code is appreciated.

推荐答案

Asserts是一种显式检查代码所做假设的方法,的bug通过缩小可能的问题可能是什么。它们通常仅在您的应用程序的特殊调试构建中进行评估,因此它们不会减慢最终发布版本。

Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version.

假设您编写了一个函数以指针作为参数。有一个很好的机会,你的代码将假设指针是非NULL,所以为什么不显式检查与断言?方法如下:

Let's say you wrote a function that took a pointer as an argument. There's a good chance that your code will assume that the pointer is non-NULL, so why not explicitly check that with an assertion? Here's how:

#include <assert.h>

void function(int* pointer_arg)
{
    assert(pointer_arg != NULL);

    ...
}

是assert的表达式必须不会有副作用,因为它们不会出现在发布版本中。所以永远不要这样做:

An important thing to note is that the expressions you assert must never have side effects, since they won't be present in the release build. So never do something like this:

assert(a++ == 5);

有些人还喜欢在他们的断言中添加一些信息,因为一个字符串总是为真,你可以这样写:

Some people also like to add little messages into their assertions to help give them meaning. Since a string always evaulates to true, you could write this:

assert((a == 5) && "a has the wrong value!!");

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

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