5.4 Get value of a certain position

Getting tired of only using List_isempty to terminate? Here’s a slight twist. Let us write a subroutine to return the value of the item at “index” n. The item has an index of 0.

The code is as follows;

 
1int List_getvalue(struct List *pList, unsigned index) 
2{ 
3  return List_isempty(pList) ? -1 :  
4           (index == 0) ? List_getfirstvalue(pList) :  
5             List_getvalue(List_getrest(pList), index-1);  
6}

Line 3 return -1 because the list is empty. If the list if not empty, then the right hand side of : is evaluated.

Line 4 returns the first value of the list because index is 0. If index is not 0, then the right hand side of : is evaluated.

Line 5 takes the rest of the list, decrease index by one, and calls the subroutine again. Whatever this invocation returns, the same value is returned.