Home > Backend Development > C++ > When Should You Use `nullptr` in C ?

When Should You Use `nullptr` in C ?

Susan Sarandon
Release: 2024-11-09 09:38:02
Original
257 people have browsed it

When Should You Use `nullptr` in C  ?

When to Use nullptr

In C code, pointers can be initialized to conceptually equivalent values: nullptr, NULL, or 0. While these values all indicate a null pointer, nullptr offers several advantages.

Overloaded Function Invocation

Consider the following overloaded functions:

void f(char const *ptr);
void f(int v);
Copy after login

In the absence of nullptr, the following call would lead to ambiguity:

f(NULL);  //which function will be called?
Copy after login

However, using nullptr clarifies the intended function invocation:

f(nullptr); //first function is called
Copy after login

Template Specialization for nullptr

Additionally, nullptr allows for template specialization specifically for null pointers. Consider the following template:

template<typename T, T *ptr>
struct something{};                     //primary template
Copy after login

The following partial specialization can be defined for nullptr:

template<>
struct something<nullptr_t, nullptr>>{};  //partial specialization for nullptr
Copy after login

This enables creating a dedicated overload for handling nullptr arguments:

template<typename T>
void f(T *ptr);   //function to handle non-nullptr argument

void f(nullptr_t); //an overload to handle nullptr argument!!!
Copy after login
Copy after login

Type Deduction for nullptr

In templates, the type of nullptr is deduced as nullptr_t. This simplifies the code, as seen below:

template<typename T>
void f(T *ptr);   //function to handle non-nullptr argument

void f(nullptr_t); //an overload to handle nullptr argument!!!
Copy after login
Copy after login

The above is the detailed content of When Should You Use `nullptr` in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template