我们什么时候应该使用断言用C? [英] When should we use asserts in C?

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

问题描述

我写在C函数作为一个风格问题,什么时候很好用断言相比,返回错误code。比方说在功能划分两个数字。我断言除数是非零或者我应该返回一个错误code?
请举些例子,如果可以的话,要区分清楚。

I am writing a function in C. As a matter of style, when is it good to use assert compared to returning an error code. Lets say the function is dividing two numbers. Should I assert the divisor be non-zero or should I return an error code? Please give more examples, if you can, to make the distinction clear.

推荐答案

断言中止的过程,而是变成了无操作时程序与<编译code> -DNDEBUG ,所以这是一个相当粗糙的调试工具,没有什么比这更。您应该只使用断言来检查的情况说:不可能发生的,例如违反算法的不变量或后置条件,但可能的的输入验证(当然不是在图书馆)。当检测到来自客户端的输入无效,友好并返回一个错误code。

assert aborts the process, but is turned into a no-op when the program is compiled with -DNDEBUG, so it's a rather crude debugging tool and nothing more than that. You should only use assert to check for situations that "can't happen", e.g. that violate the invariants or postconditions of an algorithm, but probably not for input validation (certainly not in libraries). When detecting invalid input from clients, be friendly and return an error code.

一个例子使用的断言可能是:你已经实现了一个非常聪明的排序算法,并要检查是否真的排序。由于排序功能应该只是工作,因此不返回一个值,你不能在不改变API添加错误的回报。

An example use of assert could be: you've implemented an incredibly smart sorting algorithm and you want to check whether it really sorts. Since the sorting function is supposed to "just work" and therefore doesn't return a value, you can't add error returns without changing the API.

void sort(int *a, size_t n)
{
    recursive_super_duper_sort(a, 0, n);
    assert(is_sorted(a, n));
}

static bool is_sorted(int const *a, size_t n)
{
    for (size_t i=0; i<n-1; i++)
        if (a[i] > a[i+1])
            return false;

    return true;
}

在从长远来看,你真的想为这种事情而不是断言合适的单元测试框架,但它是作为一个临时的调试工具很有用。

In the long run, you'd really want a proper unit testing framework for this kind of thing instead of assert, but it's useful as a temporary debugging tool.

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

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