๐ŸŒ
Quora
quora.com โ€บ How-do-you-return-a-null-pointer-in-C
How to return a null pointer in C - Quora
Answer (1 of 7): โ€œHow do you return a null pointer in C?โ€ This will do it: [code]return (void*)0; [/code]Enjoy your null pointer!
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ returning reference of null pointer
r/cpp_questions on Reddit: Returning reference of NULL pointer
July 18, 2021 -

In following function I'm trying find a node in Binary tree that matches the key. I'm passing reference node pointer as smart pointer and this function returns a refernce to node pointer.

How can I return NULL ? As the return value of function is std::unique_ptr<node>& so it is supposed to return a reference.

std::unique_ptr<node>& BST::ReturnNodePrivate(const int& key, std::unique_ptr<node> &ptr){
    if(NULL != ptr){
        if(ptr->key == key){
            return ptr;
         } 
    } 
     else{ 
        return NULL; 
     } 
}

How can I return NULL ?

Discussions

Return NULL in C++ - C++ Forum
And I guess you could throw and do try/catch, though I find abusing that for non errors to be a bit of a bad idea. ... Provide an output parameter to store the found book, then return a boolean success/fail. More on cplusplus.com
๐ŸŒ cplusplus.com
How do I return a Null Pointer in a function C++ - Stack Overflow
As Chris suggested, try using std::find_if algorithm. ... Looks like you just have to return Null, nullptr, or 0. More on stackoverflow.com
๐ŸŒ stackoverflow.com
c++ - returning NULL pointer in C - Stack Overflow
If you are using C++ (and maybe C++11) please use nullptr ... @DavidHeffernan look on answers. They are completely different. Somebody tells U cant return NULL, its temporary object, and somebody this is absolutly ok. ... @Dima Read the final sentence here. Where you ask about references. Which is what you asked last time. My guess is that you actually are interested in references. Look at the code in this question. Who owns the object whose address is stored in ptr? Who is going to ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to return an invalid reference?
I want to return an invalid reference in this function. Something that I can then check using IsValid() for example. These returns only work for pointers. (NULL, nullptr, 0)โ€ฆ Any way to do it? Thank you so much!! More on forums.unrealengine.com
๐ŸŒ forums.unrealengine.com
16
1
January 13, 2023
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 278740
Return NULL in C++ - C++ Forum
Hello, I'd like to if a book not find, the below method(findBookByAuthorName) return NULL. or do you have a better idea? Thanks ... The return type could be std::otional<book> (requires C++17) "The class template std::optional manages an optional contained value, i.e.
Top answer
1 of 4
13

NULL is a pointer literal which is defined to contain a special value.

One possible definition is:

#define NULL ((void *)0)

For more detail you can read this faq

About const string& foo(), I believe you mean C++'s std::string. std::string has no implicit constructor that initialize it with NULL pointer. So you should use some exception or empty string to indicate an error to the caller. (If you are not throwing, you must return an std::string. Even if the object returned is local, its life is prolonged when kept in a local constant reference. But returning some other type and expecting an implicit conversion is not a good idea.)

Answer to your question: Because NULL is a literal, no temporary object may be created most of the time and actual value can be directly returned to the caller.

2 of 4
3

This function

const string& foo(); 

does not return a pointer. It returns a constant reference to an object of type std::string. So its return value may not be assigned to a pointer.

According to the C++ Standard

4.10 Pointer conversions [conv.ptr]

1 A null pointer constant is an integer literal (2.14.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. Such a conversion is called a null pointer conversion. Two null pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4). A null pointer constant of integral type can be converted to a prvalue of type std::nullptr_t. [ Note: The resulting prvalue is not a null pointer value. โ€”end note ]

So when you use null pointer constant defined with macro NULL it is assigned to the return pointer of the function that will contain null pointer value of type node *

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ null-pointer-in-c
NULL Pointer in C - GeeksforGeeks
By specifically mentioning the NULL pointer, the C standard gives a mechanism using which a C programmer can check whether a given pointer is legitimate or not. The malloc() function returns the NULL pointer when the memory allocation is failed. We ...
Published ย  January 10, 2025
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ understanding-nullptr-c
Understanding nullptr in C++ - GeeksforGeeks
#include <iostream> using namespace std; int main() { int* ptr = nullptr; if (ptr) cout << "true"; else cout << "false"; } ... Explanation: A null pointer evaluates to false in a conditional expression, while a valid pointer evaluates to true.
Published ย  4 days ago
๐ŸŒ
Quora
quora.com โ€บ Can-you-return-null-in-C
Can you return null in C++? - Quora
Answer (1 of 10): If you are interfacing with C and dealing with pointers you can return a pointer to an object. That pointer can be NULL, if the function fails or actually succeeds but returns a null value. Because NULL is universally represented as a pointer to address [code ]0x00000000[/code]...
๐ŸŒ
Eskimo
eskimo.com โ€บ ~scs โ€บ cclass โ€บ notes โ€บ sx10d.html
10.4 Null Pointers
(A null pointer used in this way is analogous to the EOF value that functions like getchar return.) As an example, let us write our own version of the standard library function strstr, which looks for one string within another, returning a pointer to the string if it can, or a null pointer if it cannot.
๐ŸŒ
Unreal Engine
forums.unrealengine.com โ€บ development โ€บ programming & scripting โ€บ c++
How to return an invalid reference? - C++ - Epic Developer Community Forums
January 13, 2023 - I want to return an invalid reference in this function. Something that I can then check using IsValid() for example. These returns only work for pointers. (NULL, nullptr, 0)โ€ฆ Any way to do it? Thank you so much!!
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ cpp โ€บ extensions โ€บ nullptr-cpp-component-extensions
nullptr (C++/CLI and C++/CX) | Microsoft Learn
June 25, 2025 - Assignment of constant 0 to an object handle produces a boxed Int32 and a cast to Object^. The following code example demonstrates that the nullptr keyword can be used wherever a handle, native pointer, or function argument can be used.
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ null pointer in c | a detailed explanation with examples
Null Pointer In C | A Detailed Explanation With Examples
May 3, 2024 - foo(nullptr) calls the version of foo() that takes a std::nullptr_t parameter and prints- "Null pointer version". The main() function returns 0, indicating successful execution to the operating system.
๐ŸŒ
LLVM
releases.llvm.org โ€บ 19.1.0 โ€บ tools โ€บ clang โ€บ tools โ€บ extra โ€บ docs โ€บ clang-tidy โ€บ checks โ€บ modernize โ€บ use-nullptr.html
clang-tidy - modernize-use-nullptr โ€” Extra Clang Tools 19.1.0 documentation
void assignment() { char *a = nullptr; char *b = nullptr; char c = 0; } int *ret_ptr() { return nullptr; } ... Semicolon-separated list of regular expressions to match pointer types for which implicit casts will be ignored.
Top answer
1 of 9
29

I think you need something like

CopyNormal* Sphere::hit(Ray ray) {
   //stuff is done here
   if(something happens) {
       return NULL;
   }
   //other stuff
   return new Normal(something, somethingElse);
}

to be able to return NULL;

2 of 9
29

There are several fairly standard ways of doing this. There are different tradeoffs for the methods, which I'm not going to go into here.

Method 1: Throw an exception on failure.

CopyNormal Sphere::hit(Ray ray)
{
   //stuff is done here
   if(something happens) {
       throw InvalidIntersection;
   }
   //other stuff
   return Normal(something, somethingElse);
}

void example(Ray r)
{
   try {
     Normal n = s.hit(r);
     ... SUCCESS CASE ...
   }
   catch( InvalidIntersection& )
   {
      ... FAILURE CASE ...
   }
}

Method 2 return a pointer to a newly allocated object. (You could also use smart pointers, or auto_ptrs to make this a little neater).

CopyNormal* Sphere::hit(Ray ray)
{
   //stuff is done here
   if(something happens) {
       return NULL
   }
   //other stuff
   return new Normal(something, somethingElse);
}

void example(Ray ray)
{
  Normal * n = s.hit(ray);
  if(!n) {
     ... FAILURE CASE ...
  } else {
    ... SUCCESS CASE ...
    delete n;
  }
}

Method 3 is to update an existing object. (You could pass a reference, but a convention I use is that any output parameter is passed by pointer).

Copybool Sphere::hit(Ray ray, Normal* n)
{
   //stuff is done here
   if(something happens) {
       return false
   }
   //other stuff
   if(n) *n = Normal(something, somethingElse);
   return true;
}

void example(Ray ray)
{
  Normal n;
  if( s.hit(ray, &n) ) {
     ... SUCCESS CASE ...
  } else {
     ... FAILURE CASE ...
  }
}

Method 4: Return an optional<Normal> (using boost or similar)

Copyoptional<Normal> Sphere::hit(Ray ray)
{
   //stuff is done here
   if(something happens) {
       return optional<Normal>();
   }
   //other stuff
   return optional<Normal>(Normal(something, somethingElse));
}

void example(Ray ray)
{
  optional<Normal> n = s.hit(ray);
  if( n ) {
     ... SUCCESS CASE (use *n)...
  } else {
     ... FAILURE CASE ...
  }
}
Top answer
1 of 5
5

NULL is a pointer value - or rather a null-pointer value.

NULL means that the function can't find where your pointer should point to - for example if you want to open a file, but it doesn't work your file pointer is returned as NULL. So you can test the value of a pointer and check to see if it worked or not.

If you are writing a routine

int length()

then you could return a negative value if length is unable to read the length of whatever you send it - this would be a way of indicating an error, because normally lengths can never be negative....

2 of 5
3

It is a matter of convention and you should clearly have one in your head and document it (at least in comments).

Sometimes a pointer really should always point to a valid address (see this intSwap example, both arguments should be valid pointers). At other times, it should either be such a valid address, or be NULL. Conceptually the pointer type is then by convention a sum type (between genuine pointer addresses and the special NULL value).

Notice that the C language does not have a type (or a notation) which enforces that some given pointer is always valid and non-null. BTW, with GCC specifically, you can annotate a function with __attribute__ using nonnull to express that a given argument is never null.

A typical example is FILE* pointers in <stdio.h>. The fopen function is documented to be able to return NULL (on failure), or some valid pointer. But the fprintf function is expecting a valid pointer (and passing NULL to it as the first argument is some undefined behavior, often a segmentation fault; and UB is really bad).

Some non-portable programs even use several "special" pointer values (which should not be dereferenced), e.g. (on Linux/x86-64) #define SPECIAL_SLOT (void*)((intptr_t)-1) (which we know that on Linux it is never a valid address). Then we could have the convention that a pointer is a valid pointer to a valid memory zone, or NULL or SPECIAL_SLOT (hence, if seen as an abstract data type, it is a sum type of two distinct invalid pointers NULL and SPECIAL_SLOT and the set of valid addresses). Another example is MAP_FAILURE as result of mmap(2) on Linux.

BTW, when using pointers in C to heap allocated data (indirectly obtained with malloc), you also need conventions about who is in charge of releasing the data (by using free, often thru a supplied function to free a data and all its internal stuff).

Good C programming requires many explicit conventions regarding pointers, and it is essential to understand them precisely and document them well. Look for example[s] into GTK. Read also about restrict.

๐ŸŒ
cppreference.com
en.cppreference.com โ€บ cpp โ€บ language โ€บ nullptr
nullptr, the pointer literal (since C++11) - cppreference.com
August 12, 2024 - There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL. ... Demonstrates that nullptr retains the meaning of null pointer constant even if it is no longer a literal. ... #include <cstddef> #include <iostream> template<class T> constexpr T clone(const T& t) { return t; } void g(int*) { std::cout << "Function g called\n"; } int main() { g(nullptr); // Fine g(NULL); // Fine g(0); // Fine g(clone(nullptr)); // Fine // g(clone(NULL)); // ERROR: non-literal zero cannot be a null pointer constant // g(clone(0)); // ERROR: non-literal zero cannot be a null pointer constant }
๐ŸŒ
cppreference.com
en.cppreference.com โ€บ c โ€บ language โ€บ nullptr
Predefined null pointer constant (since C23) - cppreference.com
It is a non-lvalue of type nullptr_t. nullptr can be converted to a pointer types or bool, where the result is the null pointer value of that type or false respectively. ... Demonstrates that a copy of nullptr can also be used as a null pointer constant. ... #include <stddef.h> #include <stdio.h> ...
Top answer
1 of 4
5

The draft C++ standard in appendix C.4 C Standard library which is non-normative says:

The macro NULL, defined in any of <clocale>, <cstddef>, <cstdio>, <cstdlib>, <cstring>, <ctime>, or <cwchar>, is an implementation-defined C++ null pointer constant in this International Standard (18.2).

the respective normative sections agree for example 18.2 says:

The macro NULL is an implementation-defined C++ null pointer constant in this International Standard (4.10).194

which would mean if you are using the those particular headers NULL should be compatible with nullptr and then I would just use nullptr.

In appendix D which covers compatibility does not seem to make a similar statement for .h header files, so although we would expect that NULL and nullptr should be compatible null pointer constants and we would be surprised if they were not from the standard point of view it seems at minimum to be underspecified. Which leaves us with a dilemma, from a practical perspective we are pretty sure they are compatible but we don't have enough information from the standard to prove it.

So I would use NULL as defined by the specific header file you are using or we can use != 0 since fortunately both C99 and C++11 tell us that 0 is a null pointer constant.

From C99 section 6.3.2.3 Pointers:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

and:

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined

and C++ section 4.10 Pointer conversions tells us:

A null pointer constant is an integer literal (2.14.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.[...]

2 of 4
2

They are exactly and totally equivalent, so use nullptr because NULL is a primitive C-ism that has no reason to live anymore.

But in the case of CreateEventEx you have the hilarious bonus of not all invalid HANDLEs being nullptr, some of them are INVALID_HANDLE_VALUE instead. So neither is really "safe" in the case of HANDLE. You need to check exactly what CreateEventEx returns on failure.