How do I use nullptr in C++11?

In C++11, `nullptr` is introduced as a type-safe null pointer constant. It provides a way to represent null pointers more safely compared to using the traditional `NULL` macro or integer value `0`. Below, I will demonstrate how to use `nullptr` in different scenarios.


#include <iostream>

void foo(int* ptr) {
    if (ptr == nullptr) {
        std::cout << "Pointer is null!" << std::endl;
    } else {
        std::cout << "Pointer is valid!" << std::endl;
    }
}

int main() {
    int* p1 = nullptr; // Using nullptr
    int value = 5;
    int* p2 = &value; // Pointer to an integer

    foo(p1); // Output: Pointer is null!
    foo(p2); // Output: Pointer is valid!

    return 0;
}
    

C++ nullptr C++11 null pointer programming coding