The correct way to return an error code for the return size_t function

I have a function that examines an array and returns the index of the array if the probe succeeds.

In my code, for clarity, I made each type with respect to the index of the array a type_t .

What is the preferred way to maintain this clarity for this function? Should I take a pointer argument to an error variable and set this?

 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 } 

Then I could use it as

 index = linsearch(parray, x, 0, n - 1); if (index == -1) ... not found 
+5
source share
2 answers

Another way without losing size_t (size_t is the correct type for array indices) is to return the index value to a pointer and a return code in the form of a logical value:

  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; } 

and you can call:

 size_t index; if ( lin_search(...., &index) ) { /* use 'index' */ } 

This way you don't have to compromise using anything other than size_t , and the return type of the function still says if the index is found.

+4
source

Situations like this are not unheard of. Take, for example, the definition of fgetc that reads characters:

 int fgetc(FILE *stream); 

fgetc () reads the next character from the stream and returns it as an unsigned char conversion to int or EOF at the end of the file or error.

This function returns a value that can be added to unsigned char on success, and returns EOF (usually -1) on error.

Another example is ftell , which reports the current offset in a file:

 long ftell(FILE *stream); 

Upon successful completion ... ftell () returns the current offset. Otherwise, -1 is returned, and errno is an error to indicate.

File offsets are always non-negative, so returning a negative value is an error message.

Therefore, I think that changing the return type to long would be acceptable for such a case.

+1
source

Source: https://habr.com/ru/post/1241320/


All Articles