5.2 List length

How many items are there in a list? Let us consider the cases:

It is coded as follows:

 
1unsigned List_length(struct List *pList) 
2{ 
3  return (pList == NULL) ? 0 :  
4           (List_isempty(pList)) ? 0 :  
5             (1 + List_length(List_getrest(pList)));  
6}

Line 3 checks to see if the pointer to the list itself is NULL. This is not strictly required if we can assume that the parameter is at least a valid pointer to a list. If the pointer is not NULL, then the expression returns the right hand side of the : operator.

Line 4 checks to see if the list pointed to by pList is empty or not. If so, the embedded ?: expression returns 0. Otherwise, the right hand side of : is evaluated.

Line 5 evaluates iff the pointer is not NULL, and the list pointed to by the pointer is not empty. At this point, we return the sum of 1 (for the first item in the list) and the length of the rest of the list.