1

I am trying to write a function that takes a linked list, an index and returns the value at the index+1 position.

int getData(list *l, int index) {
    if(...) { 
        ...
        return result; // this could be -1
    }

    else {
        return -1;
    }
}

In C you return a value of -1 when the function fails (as a way to let the user know that the call failed because of bad input). However, because the return type of this function is int, it includes the value of -1 (-1 as a number, as well ass -2, -3 etc)

My question is: Is there a mechanism in which you can return from your function and make the user of the function aware that the returned value is in fact an error and not a value?

Shawn
  • 47,241
  • 3
  • 26
  • 60
bem22
  • 276
  • 1
  • 14
  • C or C++? It seems like you mistakenly added a c++ tag to this question. – Coral Kashri Oct 14 '19 at 10:29
  • For C, look into `errno.h` -- see this as well https://stackoverflow.com/questions/503878/how-to-know-what-the-errno-means – gstukelj Oct 14 '19 at 10:30
  • @gst `errno` is for system functions, not user functions. – Barmar Oct 14 '19 at 10:31
  • @Barmar couldn't a user function set the value of `errno`? Would that be considered bad practice? – gstukelj Oct 14 '19 at 10:32
  • @gst It's allowed, just unusual. You have to be careful because it can be changed out from under you if you call other system functions. – Barmar Oct 14 '19 at 10:40
  • I might be naive, but for me it seems that you need something like while (index++ < endIndex) currentNode = currentNode->next; return currentNode->value; – Lajos Arpad Oct 14 '19 at 12:08

1 Answers1

4

Return the value by passing a pointer and make the return value an error statement:

int getData(list *l, int inIndex, int* outIndex) {
    if(...) { 
        ...
        *outIndex = result;
        return 0;
    }

    else {
        return -1;
    }
}
RoQuOTriX
  • 2,871
  • 14
  • 25