我有一個函數,探測一個數組,並返回一個數組索引,如果探測成功。正確的方法返回函數返回的錯誤代碼size_t
在我的代碼中,爲了清楚起見,我已經對數組索引a 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
你可以將你的函數切換到(簽名)'ssize_t'嗎? –
我沒有'ssize_t'。你能否返回'SIZE_MAX'來表示失敗? –
'ssize_t'不是標準C(它是POSIX)。不過,C確實有'ptrdiff_t'。也就是說,((size_t)-1')總是定義爲(SIZE_MAX);我們可以使用'#define LIN_SEARCH_ERR((size_t)-1)'或類似的方法。 –