[英]What are the ramifications of returning the value -1 as a size_t return value in C?
[英]Correct way to return an error code for function returning size_t
我有一个探测数组的函数,如果探测成功,则返回一个数组索引。
在我的代码中,为清楚起见,我已将与数组索引有关的每个类型都type_t
。
保留此功能清晰性的首选方法是什么? 我应该使用指向错误变量的指针参数并进行设置吗?
inline size_t
lin_search(const double *pxa, const double x, const size_t idxlow, const size_t idxhigh)
{
for (size_t i = idxlow; i < idxhigh; i++)
{
if (pxa[i] <= x && pxa[i+1] > x)
return i;
}
return -1; // If I change the return type to f.ex long int this works
// but I am no longer consistent
}
然后我可以将其用作
index = linsearch(parray, x, 0, n - 1);
if (index == -1)
... not found
另一种不“丢失” size_t(size_t 是数组索引的正确类型)的方法是返回指针中的索引值并以布尔值返回代码 :
bool
lin_search(...., size_t *index) {
bool found = false;
for (size_t i = idxlow; i < idxhigh; i++) {
if (pxa[i] <= x && pxa[i+1] > x) {
found = true;
*index = i;
break;
}
}
return found;
}
您可以致电:
size_t index;
if ( lin_search(...., &index) ) {
/* use 'index' */
}
这样,您不必折衷使用size_t
以外的其他东西,并且函数返回类型仍会指示是否找到索引。
这样的情况并非闻所未闻。 以fgetc
的定义为例,该定义读取字符:
int fgetc(FILE *stream);
fgetc()从流中读取下一个字符,并以无符号字符的形式将其返回给int,或者在文件或错误结束时返回EOF。
此函数返回一个值,该值可以在成功时转换为unsigned char
,在失败时返回EOF
(通常为-1)。
另一个示例是ftell
,它报告文件中的当前偏移量:
long ftell(FILE *stream);
成功完成后,... ftell()返回当前偏移量。 否则,返回-1并将errno设置为指示错误。
文件偏移量总是非负的,因此返回负值是报告错误的方式。
因此,我认为将返回类型更改为long
在这种情况下是可以接受的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.