Skip to content

The Power of Zero: What is NULL anyway?

I remember when I was first learning to code, I thought 0 and NULL were the same thing. They both mean "nothing," right?

But then I got my first NullPointerException (or a segmentation fault), and I realized that in computing, there is a massive difference between "the number zero" and "no value at all."

Let's look at why 0 is powerful, but NULL is dangerous.

The Big Picture: The Empty Box Analogy

Imagine a row of lockers.

[ L1: 42 ] [ L2: 0 ] [ L3: ??? ]
  • Locker 1 (L1): Contains the number 42.
  • Locker 2 (L2): Contains the number 0. The locker exists, and it is holding a specific value.
  • Locker 3 (L3): This is NULL. The locker might not even exist, or if it does, it has no value inside it.

In Programming:

  • 0 is a value. You can add it to other numbers, or print it.
  • NULL is a pointer that points to nowhere. If you try to ask NULL for its value, your program crashes because there is no locker to look in!

Wait, but why?

Why do we even have NULL?

Tony Hoare (who invented NULL in 1965) calls it his "Billion Dollar Mistake." He added it because it was easy to implement, but it has caused countless crashes and security vulnerabilities since then.

Modern languages like Rust and Swift try to fix this by making it impossible to have a "null" value by default. You have to explicitly say "this might be nothing" using things like Option or Optional.


Common gotchas

  • I always forget that in C, NULL is often just a macro for (void*)0. This means that at a low level, NULL is actually the number zero, but the computer treats it like a special "prohibited" address.
  • Watch out for "Falsy" values: In JavaScript, 0, "", and false are all "falsy," but they aren't null. If you check if (my_number), and my_number is 0, the check will fail!

Try it yourself

Think about a search bar on a website: 1. If you search for "abc" and find 0 results, that's a value. The search happened, and the answer is zero. 2. If the user hasn't searched yet, that's NULL. The search hasn't even happened.

Treating "hasn't happened" and "result is zero" as the same thing is how bugs are born!


Further reading

— Nadeem ∅

Comments