Search⌘ K

Null Pointer

Explore the concept of the null pointer in C++ and understand why the nullptr keyword improves code clarity by eliminating ambiguity between integer zero and null pointers. This lesson covers pointer initialization, comparison, and generic programming challenges solved by nullptr.

We'll cover the following...

Before C++11, 0 was often used to represent an empty or null value when the NULL macro was not applicable. The issue with the literal 0 is that it can be the null pointer (void*)0 or the number 0. This is defined by the context.

Therefore, a small program with the number 0 should be confusing.

C++
#include <iostream>
#include <typeinfo>
int main(){
std::cout << std::endl;
int a= 0;
int* b= 0;
auto c= 0;
std::cout << typeid(c).name() << std::endl;
auto res= a+b+c;
std::cout << "res: " << res << std::endl;
std::cout << typeid(res).name() << std::endl;
}

The variable c is of type int, and the variable res is of type pointer to int: int*. Pretty simple, right? The expression a+b+c in line ...