0. Null

The getchar() function of programming language C reads a character from the standard input stream and returns it. However, if the stream reaches the end (EOF) or an error occurs, it returns the constant EOF. It defines this constant as a negative integer value.

Since the character is a single byte, it seems that the return value type could be char. However, the return type cannot be char because it must be a type that can represent 257 values at least, which contain 256 possible values of char and a special value representing EOF or an error.

Thus, some APIs return two or more kinds of result †1, and require the caller to check the return value to determine that kind. And they define the constant to show special results †2 (e.g., EOF in the above example).

†1 Expressions such as normal process and exception handling are not appropriate, because EOF is not an exception for getchar(). It provides two types of results: getting a character from the stream, detecting EOF or an input error.

†2 So-called sentinel value. See Wikipedia [1].

And some APIs that return a pointer return NULL (a null pointer) to indicate failure. For example, fopen() and malloc() do so if they cannot meet the request. As well, strstr() and strchr() do so if they cannot find the target. If you use the pointer of the return value without checking whether it is NULL or not, you will be in for a scary surprise. That is because what happens is not set in stone.

An object-oriented language often defines null, nil, etc. to indicate that the reference does not refer to anything, as well as a null pointer of C. They are called null references. The description from Wikipedia [2] is quoted below:

a null pointer or null reference has a value reserved for indicating that the pointer or reference does not refer to a valid object.

However, in Java, for example, dereferencing a null reference only throws a prescribed exception and nothing terrible happens. You just have to make sure that you don't forget to check if the reference is null with if. Even if you do, what happens is just throwing an exception.

But checking null with if, the so-called null check, is not the only way to handle a null reference correctly. Let's consider how to handle null references in some languages.

References

  1. Wikipedia, Sentinel value

  2. Wikipedia, Null pointer