Consider the following C++ program that shows problem with NULL (need of nullptr)
16:13: error: call of overloaded 'fun(NULL)' is ambiguous fun(NULL);
What is the problem with above program?
NULL is typically defined as (void *)0 and conversion of NULL to integral types is allowed. So the function call fun(NULL) becomes ambiguous.
How does nullptr solve the problem?
In the above program, if we replace NULL with nullptr, we get the output as “fun(char *)”.
nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.
As a side note, nullptr is convertible to bool.
There are some unspecified things when we compare two simple pointers but comparison between two values of type nullptr_t is specified as, comparison by <= and >= return true and comparison by < and > returns false and comparing any pointer type with nullptr by == and != returns true or false if it is null or non-null respectively.
can compare x is null
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Understanding static_assert in C++ 11
- Understanding "register" keyword in C
- Understanding constexpr specifier in C++
- Understanding "extern" keyword in C
- OpenCV | Understanding Brightness in an Image
- OpenCV | Understanding Contrast in an Image
- Understanding "volatile" qualifier in C | Set 1 (Introduction)
- Understanding "volatile" qualifier in C | Set 2 (Examples)
- Understanding Lvalues, PRvalues and Xvalues in C/C++ with Examples
- Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
- Difference between Sentinel and Counter Controlled Loop in C
- Why do we need reference variables if we have pointers
- What are the differences between C and Embedded C?
- Similarities and Difference between Java and C++
Improved By : shubham_singh