C++ <cstring> - NULL constant
NULL macro expands to a null pointer constant. A null pointer constant is either an integral constant expression that evaluates to zero (such as 0 or 0L), or a value of type nullptr_t (such as nullptr).
A null pointer constant can be converted to any pointer and pointer to member type. Such conversion results in the null pointer value of that type.
A pointer whose value is null does not point to an object or a function. Dereferencing a null pointer shows undefined behavior. All pointers of the same type whose value is also null compares equal.
To initialize a pointer to null or to assign the null value to an existing pointer, the null pointer literal nullptr, the null pointer constant NULL, or the implicit conversion from the integer value 0 may be used.
Different ways of creating null pointers are given below:
//initialize a pointer to null int *ptr1 = NULL; int *ptr2 {NULL}; int *ptr3 = 0; int *ptr4 {0}; //existing pointer is assigned to null int *ptr5; ptr5 = NULL; int *ptr6; ptr6 = 0; //using nullptr literal int *ptr7; ptr7 = nullptr; int *ptr8 = nullptr;
Null pointers can be used to indicate the absence of an object, or as an indicator of error conditions (for example - dynamic_cast). Normally, a function with a pointer argument generally needs to check if the value is null and handle that case differently (for example, the delete expression does nothing when a null pointer is passed).
To check for a null pointer the following statement can be used:
if(ptr) //succeeds if ptr is not null if(!ptr) //succeeds if ptr is null
Example:
In the example below, a function called print is created to print the value stored in the passed pointer. The functions handles the null pointer differently and print a message in that case.
#include <iostream> #include <cstring> using namespace std; void print(int *ptr) { if (!ptr) cout<<"print(int*): It is null.\n"; else cout<<"print(int*): "<<*ptr<<'\n'; } int main() { int x = 25; //using print function with null pointer int *p1 = NULL; print(p1); //using print function with pointer int *p2 = &x; print(p2); return 0; }
The output of the above code will be:
print(int*): It is null. print(int*): 25
❮ C++ <cstring> Library