Ill-Advised C++ Rant, Part 1 December 11th, 2015
When something new arrives, one should look at what it replaces. Sometimes this is so you'll learn the benefits of the new thing, but sometimes it's so you'll discover the echoes of mistakes made in the past, the paper-trail of mishaps that led to this state.
In C there were pointers. You could set them to any value, but you could
also set them to NULL
. NULL is a "null pointer constant", a pointer
which does not point to anything.
C++11 deprecates NULL, instead preferring the use of nullptr
. nullptr is
a "null pointer constant", a pointer which does not point to anything.
Wait, I hear you cry in a befuddled tone, we already had a null pointer constant, did we not? Why do we need a new one? No, we didn't. We never had a null pointer constant in C++. You see, the C++ committee changed the definition of NULL from its old definition:
#define NULL (void *)0
to its new definition:
#define NULL 0
That's right, NULL in C++ is no longer a pointer, it's an integer. Literally the sole reason for NULL to exist is to define a null pointer, and someone decided to break that. They created a world where your null pointer is an integer and not a pointer, and then wonder why confusion arises between pointer and integer overloading.
If there's any lesson to be learned from this, I guess it's that idealistic
new visions should not conflict with the basic expectations of
sanity already laid in place. While the change of NULL to 0
may have had
good intentions behind it, if you define something as being a pointer then
the reasonable man is going to expect it to always be so.
You'll notice that the old definition of NULL is a macro, so presumably could now be changed to:
#define NULL nullptr
With that new definition we could just keep on using NULL without having to worry about it, everyone would be happy, and NULL would be fixed and become a pointer again. I'm sure the C++ guys will claim a good reason why this wasn't done, but it's too late now anyway, the die is cast.
I'm reminded of the old story of the woman who swallowed the spider to catch the fly. Do you get that inkling... that tiniest feeling at the back of your mind that there may, possibly, be a mistake being made here? Are we starting another set of wheels turning that will require fixing again?
The biggest problems in programming are the ones we create for ourselves. Every new feature added to C++ seems to exist only to correct past mistakes, mistakes that were caused by the same intentions that drive the current new features. I look forward to seeing in 10 years what new features will need to be introduced to fix the current batch of mistakes.
Written by Richard Mitton,
software engineer and travelling wizard.
Follow me on twitter: http://twitter.com/grumpygiant