The multiple faces of nothing

[… or “C, variants and the NULL”]

In C, you have a way to represent nothing. It’s NULL (all caps). NULL points to nowhere and it’s defined as “0”. Why would someone use it? Well, if you have a list and some of the elements aren’t valid, you make them NULL. Since NULL is not a valid pointer, your application will crash if you try to access it. The whole point of NULL is to provide a way to represent the nothing. There is also a nothing type “void”, which you can define anything statically, but you can make it a point of it. Since all pointers have the same size, a “void pointer” is, basically, a pointer to anything.

Also, C have the idea of “nul-terminated strings” (yes, with just one “l”.) the “nul” character is represented by “\0”, which, in practical terms, is a space of memory with the size of a “char” with the value 0 on it.

When going down to the very bits of NULL and nul, they go almost the same, except for their size.

C++ was build on top of C, but if defined NULL as a pointer pointing to the byte 0. It’s almost the same thing as the C NULL but, because it’s a pointer, it doesn’t need to be converted when you’re using a CPU which have a different size for “int”s and pointers (usually, pointers are “long int”s or even more, if your CPU have more than 64 bits.)

Objective-C is a variant of C adding support for objects in a different way and the biggest “user” of Objective-C is Apple. The Apple version of Objective-C provides some basic types like lists. But, because you can’t leave an empty space in the list (which I think it similar to the way we deal with nul-terminated string), they created a NSNull object, which is a valid object, but it represents the null (which, by the way, are called “nil” in Objective-C.) It’s not an invalid memory address, as it points to a real object. The NSNull object provides just one method, “null” which returns a “nil” pointer (are you confused already?)

Now, the fun part: Most list (dictionaries actually, but the process is almost the same) operations, when you try to access an object that doesn’t exist, returns nil. But remember that the only way to leave an empty spot in a list is adding a NSNull object. So, to be really sure that something is not there, you need to check if the result is “nil” or “not an [NSNull null]”.

That’s too much stuff for nothing…