×

Nullptr in C++

What is Nullptr in C++?

A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object handle does not point to an object.

We use nullptr with managed or native code. For native and managed null pointer values, the compiler emits instructions that are suitable but distinct. See nullptr for details on how to use the C++ version of this keyword that is ISO compliant.

The __nullptr keyword, which is unique to Microsoft and only used in native code, has the same semantics as nullptr. The compiler cannot tell managed from native null pointer values when native C/C++ code uses nullptr and is built with the /clr compiler option. To make your meaning clear to the compiler, use nullptr to define a managed value or __nullptr to describe a native value.

The C# and Visual Basic equivalents of the keyword nullptr are null and Nothing, respectively.

Use of Nullptr

The keyword nullptr is permitted whenever a handle, native pointer, or function parameter may be used.

The nullptr keyword is not recognised for use with the following:

  • sizeof
  • typeid
  • throw (Object)nullptr; will also work, but throw nullptr

The following pointer types can be initialised with the nullptr keyword:

  • local pointer
  • Windows Runtime manage
  • controlled handle
  • controlled internal pointer

Before using a pointer or handle reference, the nullptr keyword can be used to check if it is null. Function calls should be properly interpreted by languages that use null pointer values for error checking. Only nullptr may be used to initialise a handle to zero. A boxed Int32 and a cast to Object are created when constant 0 is assigned to an object handle.

Example of a nullptr keyword

The following line of code illustrates how the nullptr keyword can be used at anyplace a handle, native pointer, or function parameter. Additionally, the example shows how the nullptr keyword may be used to validate a reference before using it.

Example 1:

// C++ program to display the NULL problem
#include <bits/stdC++.h>
using namespace std ;
// an integer-argument function
void fun(int N) { 
cout<< "funcion( int ) " ; 
return ;
}
// function with a char pointer parameter that is overloaded
void fun(char* s) { 
cout<< "function ( char * )" ;
return ;
}
int main()
{
	// Although calling fun(char *) would have been ideal, 
    // doing so results in a compiler error.
	fun(NULL) ;
}

Output:

What is Nullptr in C++

What is wrong with the program?

Normally, NULL is defined as (void *)0, and it is permissible to convert NULL to integral types. As a result, the function call fun(NULL) is unclear.

// This program compiles (may produce warning)
#include<stdio.h>
int main()
{
int a = NULL;
return 0;
}

How does nullptr handle this issue?

If NULL is swapped out for nullptr in the above program, the output reads "fun(char *)".

The keyword nullptr can be used whenever NULL is anticipated. Similar to NULL, Nullptr is implicitly convertible and comparable to any pointer type. It is not inherently convertible or equivalent to integral types, in contrast to NULL.

Example 2:

// The compilation of this program fails.
#include<stdio.h>
int main()
{
int a = nullptr;
}

Output:

What is Nullptr in C++

As an aside, nullptr can be converted to Boolean value.

Example 3:

// This program compiles
#include<iostream>
using namespace std;


int main()
{
    int *pointer = nullptr;


    // Below line compiles
    if (pointer) {
cout<< "true"; 
        }
    else { 
cout<< "false"; 
        }
    return 0;
}

Output:

What is Nullptr in C++

When comparing two simple pointers, there are some unspecified factors, but when comparing two values of type nullptr t, it is specified that comparisons by = and >= return true and comparisons by and > returns false, and comparisons by == and!= return true or false depending on whether the value is null or not.

Example 4:

// Program in C++ that displays comparisons with nullptr
#include <bits/stdC++.h>
using namespace std;


// Driver program to test nullptr behaviour
int main()
{
	// establishing two variables of type nullptr t, 
	// so their values are nullptr
	nullptr_t nop1, nop2;


	// Comparisons between = and >= always return true.
	if (nop1 >= nop2)
		cout<< "we can compare it " <<endl;
	else
		cout<< "we can not compare it " <<endl;


	// Initialize a pointer with value equal to nop1
	char *a = nop1; 
    // equivalent to a = nullptr
	// (a = NULL is also acceptable.)
	if (a == nullptr)
		cout<< "a is null" <<endl;
	else
		cout<< "a is not null" <<endl;


	return 0;
}

Output:

What is Nullptr in C++

Related Topics

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.