Difference Between null and nullptr in C++

1. Introduction

In C++ programming, distinguishing between NULL and nullptr is important for writing clear and correct code. NULL is a macro that represents a null pointer, typically defined as 0. nullptr is a keyword introduced in C++11, representing a null pointer constant, and is meant to replace NULL in modern C++ code.

2. Key Points

1. NULL is traditionally defined as 0 or (void*)0, making it an integer type.

2. nullptr is a keyword that represents a null pointer of any pointer type.

3. nullptr provides a clearer indication of a null pointer and is type-safe.

4. Using nullptr helps in resolving ambiguity in function overloading and template instantiation.

3. Differences

NULL nullptr
An integer constant with a value of 0. A pointer type constant representing a null pointer.
Can lead to ambiguity in function overloading. Resolves ambiguity in function overloading.
Less type-safe compared to nullptr. Type-safe and preferred in modern C++.

4. Example

#include <iostream>
using namespace std;

void func(int num) {
    cout << "func(int) called" << endl;
}

void func(char *ptr) {
    cout << "func(char*) called" << endl;
}

int main() {
    // Example using NULL
    func(NULL);  // Calls func(int)

    // Example using nullptr
    func(nullptr);  // Calls func(char*)

    return 0;
}

Output:

func(int) called
func(char*) called

Explanation:

1. When func(NULL) is called, NULL is interpreted as 0, an integer, so func(int) is called.

2. When func(nullptr) is called, nullptr is a null pointer constant, so func(char*) is called.

5. When to use?

- Use nullptr in modern C++ code for clarity and type safety when dealing with null pointers.

- NULL can still be used for backward compatibility, but it is less type-safe and can lead to ambiguities, especially in function overloading scenarios.

Related C++/CPP Posts:

Difference Between Struct and Class in C++

Difference Between Pointer and Reference in C++

Difference Between null and nullptr in C++

Difference Between Array and Vector in C++

Difference Between const and constexpr in C++

Difference Between List and Vector in C++

Difference Between C and C++

Difference Between Function Overloading and Operator Overloading in C++

Difference Between Array and List in C++

Difference Between a While Loop and a Do-While Loop in C++

Difference Between new and malloc C++

Virtual Function vs Pure Virtual Function in C++

Compile Time Polymorphism vs Runtime Polymorphism in C++

Difference Between Shallow Copy and Deep Copy in C++

Difference Between Stack and Heap in C++

Copy Constructor vs Parameterized Constructor in C++

Comments