2

在“C 编程语言的 JPL 机构编码标准”中,我在规则 15 (第 14 页)下方找到了以下句子:

“这与使用总函数优于非总函数的原则是一致的。”。

我以前没有听说过“总功能”。这是什么?你能给我一些总功能的例子吗?

以下是 JPL 文档的链接。

http://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdf

4

2 回答 2

8

That's explained in the next sentence in the document:

A total function is setup to handle all possible input values, not just those parameter values that are expected when the software functions normally.

I think it's originally a mathematical term. A total function is one that has well defined behavior for all possible argument values.

An example of a non-total function is strlen(), which has undefined behavior if its argument is a null pointer, or an invalid pointer, or a pointer into an array that has no null '\0' character. (And there's no real way, at least in portable C, to make strlen() detect and handle all possible invalid arguments.)

A total function, in the sense used in the document either returns a meaningful result for all possible inputs, or detects any invalid inputs and reports an error in some well defined manner.

于 2013-10-28T23:48:37.797 回答
1

A total function is a function that has a defined (and by implication, correct) value for every possible input value. That is, JPL is saying that it's preferable to write functions that always give the right answer, not ones that only give the right answer for the range of values that someone had in mind when they were writing the function.

However, if you write a function that isn't total (its domain of applicability is smaller than the range of its input type), you should add checks that make sure that you generate an error whenever you encounter an input value that won't give a correct output, instead of continuing with invalid state.

于 2013-10-28T23:50:31.937 回答