Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Many functions have the option of returning a pointer to an object, or returning NULL if a valid pointer cannot be produced. Some functions return arrays, which appear like a pointer to an object. However, if a function has the option of returning an array, or indicating that a valid array is not possible, it should not return NULL. Instead, the function should return an empty array. Often code that calls a function that returns an array intends merely to iterate over the array elements. In this case, the calling code need not change...iterating over the elements works correctly even if the returned array is empty, and thus the calling code need not check the return value for NULL.

This situation is complicated by the fact that

There are situations in which a function may return an array on the basis of its length. If an array of length zero is being returned, NULL should not be used. An empty array must be used to ensure the caller function can handle the return value correctly.

Although C does not keep track of the length of an array. However, two popular methods have emerged to emulate this behavior. The first is to wrap the array in a struct with an integer storing the length. The second is to place a sentinel value at the end of the data in the array. This second approach is most commonly manifested in null-terminated byte strings (NTBSs).

...