我有一个探测数组的函数,如果探测成功,则返回一个数组索引.
在我的代码中,type_t为了清楚起见,我已经为数组索引a制作了所有类型.
保留此功能的清晰度的优先方法是什么?我应该将一个指针参数带到一个错误变量并设置它吗?
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
}
Run Code Online (Sandbox Code Playgroud)
然后我可以用它作为
index = linsearch(parray, x, 0, n - 1);
if (index == -1)
... not found
Run Code Online (Sandbox Code Playgroud)
另一种不“丢失” 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;
}
Run Code Online (Sandbox Code Playgroud)
您可以致电:
size_t index;
if ( lin_search(...., &index) ) {
/* use 'index' */
}
Run Code Online (Sandbox Code Playgroud)
这样,您不必妥协于使用其他东西,size_t并且函数返回类型仍然表明是否找到索引。