×

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

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 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.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 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 build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.