C++ references cannot be null.

If you are returning a reference to an object whose lifetime is not tied to the scope of the function call, like a data member, you can safely return a raw pointer (I would recommend a pointer to const).

std::string const* foo::bar() const {
    if (condition) {
        return &some_data_member;
    } else {
        return nullptr;
    }
}

If not, the best solution is to use a wrapper type like boost::optional (or std::optional in C++17). This not only allows you to return an optional object by value (which may be more performant), but is also self-documenting.

std::optional<std::string> foo::bar() const {
    if (condition) {
        return "hello, world";
    } else {
        return std::nullopt;
    }
}

Alternatively, you could return a pointer, which can be null. However, returning a raw pointer raises the question of who is responsible for deleting the dynamically allocated string. In this case, returning a std::unique_ptr would be the best option, as ownership is explicitly passed to the caller.

std::unique_ptr<std::string> foo::bar() const {
    if (condition) {
        return std::make_unique<std::string>("hello, world");
    } else {
        return nullptr;
    }
}

Or even simpler, you could return an empty string, if this is possible in your case. And honestly, this is my preferred approach (KISS).

std::string foo::bar() const {
    if (condition) {
        return "hello, world";
    } else {
        return "";
    }
}
Answer from Joseph Thomson on Stack Overflow
Top answer
1 of 5
11

C++ references cannot be null.

If you are returning a reference to an object whose lifetime is not tied to the scope of the function call, like a data member, you can safely return a raw pointer (I would recommend a pointer to const).

std::string const* foo::bar() const {
    if (condition) {
        return &some_data_member;
    } else {
        return nullptr;
    }
}

If not, the best solution is to use a wrapper type like boost::optional (or std::optional in C++17). This not only allows you to return an optional object by value (which may be more performant), but is also self-documenting.

std::optional<std::string> foo::bar() const {
    if (condition) {
        return "hello, world";
    } else {
        return std::nullopt;
    }
}

Alternatively, you could return a pointer, which can be null. However, returning a raw pointer raises the question of who is responsible for deleting the dynamically allocated string. In this case, returning a std::unique_ptr would be the best option, as ownership is explicitly passed to the caller.

std::unique_ptr<std::string> foo::bar() const {
    if (condition) {
        return std::make_unique<std::string>("hello, world");
    } else {
        return nullptr;
    }
}

Or even simpler, you could return an empty string, if this is possible in your case. And honestly, this is my preferred approach (KISS).

std::string foo::bar() const {
    if (condition) {
        return "hello, world";
    } else {
        return "";
    }
}
2 of 5
1

Anyway you wouldn't return NULL but nullptr. Also, you should be carefull with returning references from a function and make sure the reference referes to a valid, living object. returning reference to local object is wrong.

you can't return nullptr since nullptr is a pointer and string& is a reference - different types.

your options are:

  1. throw an exception
  2. use something like Optional classes (boost::optional, etc.)

personally, if I know there is a strong possibility the function may fail, I would pass the result to a reference type argument and return bool to indicate success of failure

bool SomeClass::getSomething(std::string& result)
{
     if(){result = "success 1"; return true; }
     else if(){result = "success 2"; return true; }
     return false.
}
🌐
Reddit
reddit.com › r/c_programming › can you return null from a function that returns a multidimensional ***pointer?
r/C_Programming on Reddit: Can you return NULL from a function that returns a multidimensional ***pointer?
January 17, 2022 -

I am very sure that someone told me once that NULL is defined as a pointer to void. I leafed through the K&R, and NULL was just said to be interchangeable with zero.

But either way, if I have a function that returns a 3d char array (array of arrays of strings), can I then return NULL if something goes wrong? will it be a valid return type?

Many functions that return pointers return NULL if something goes wrong - fopen for instance where you check for NULL and then perror.

But I am confused about multi-dimensional pointers.

I mean, I know that they are technically just pointers. I am unsure what the multiple asterisks do except tell the programmer how many dimensions there are. Hmmm Is this the solution?

Comments?

Discussions

Return empty string in c - Stack Overflow
I can't return NULL, because later I concatenate returned values, so it will be worse implementation, if I have to check every returned values for NULL ... If you don't return null, you're going to have to malloc every time you return an empty string because you're returning char * and not ... More on stackoverflow.com
🌐 stackoverflow.com
Returning null instead of empty string if a wrapped function returns null pointer
Hi emscripten folks, I am trying to wrap a function with the following C signature: const char* getLastError() It returns a pointer to zero-terminated C string or the NULL pointer in case no last e... More on github.com
🌐 github.com
9
September 16, 2024
String NULL? - C++ Forum
In other cases, returning an empty string was also ok (i.e., string with 0 length). It depends on what the calling function excepts. With char's is actually no different. You can return NULL, but if the calling function tried to print it, then you're going to get problems. More on cplusplus.com
🌐 cplusplus.com
How to access the return value of a C function that can return null to return an error?
Hi, simple question here, I’m trying to find how to call a C function that can return null and catch the null case to return an error relative to the function’s meaning of null; uint8_t *string_bsearch(const uint8_t *s,… More on ziggit.dev
🌐 ziggit.dev
1
0
February 11, 2024
🌐
GitHub
github.com › emscripten-core › emscripten › issues › 22574
Returning null instead of empty string if a wrapped function returns null pointer · Issue #22574 · emscripten-core/emscripten
September 16, 2024 - Hi emscripten folks, I am trying to wrap a function with the following C signature: const char* getLastError() It returns a pointer to zero-terminated C string or the NULL pointer in case no last e...
Author   emscripten-core
🌐
Cplusplus
cplusplus.com › forum › general › 44832
String NULL? - C++ Forum
I need to be able to pass something back (other than a "valid" string) but can't seem to find a tool to use. Any suggestions? Edit: Corrected a spelling problem. Thanks, L B. ... I would most likely throw an exception in this case. ... I'd also suggest throwing an exception, as firedraco says, but I think it depends on the situation. For example, in one case for me, returning the string "N/A" made sense.
Find elsewhere
🌐
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!
Top answer
1 of 16
102

StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:

Returning null is usually the best idea if you intend to indicate that no data is available.

An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.

However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.

In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.

2 of 16
101

In all the code I write, I avoid returning null from a function. I read that in Clean Code.

The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.

In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.

The analogous C# (anti-)pattern is the Try... method:

public bool TryFindPerson(int personId, out Person result);

Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:

class FindResult<T>
{
   public FindResult(bool found, T result)
   {
       this.Found = found;
       this.Result = result;
   }

   public bool Found { get; private set; }
   // Only valid if Found is true
   public T Result { get; private set;
}

public FindResult<Person> FindPerson(int personId);

...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework. That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).

So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.

If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:

public Person GetPerson(int personId);

...and then I'd throw an exception if it was invalid. The Get... prefix implies that the caller knows it should succeed.

🌐
Eskimo
eskimo.com › ~scs › cclass › notes › sx10d.html
10.4 Null Pointers
Notice that the function is declared as returning (and does in fact return) a pointer-to-char. We can use mystrstr (or its standard library counterpart strstr) to determine whether one string contains another: if(mystrstr("Hello, world!", "lo") == NULL) printf("no\n"); else printf("yes\n");
🌐
W3Schools
w3schools.com › c › c_null.php
C NULL
You can compare a pointer to NULL to check if it is safe to use. Many C functions return NULL when something goes wrong. For example, fopen() returns NULL if a file cannot be opened, and malloc() returns NULL if memory allocation fails.
🌐
Reddit
reddit.com › r/c_programming › how do i print out the null value in a string?
r/C_Programming on Reddit: How do I print out the null value in a string?
December 4, 2023 -

I learned in C that a string ends with a null value, "\0". How do I print out this null value in C?

I tried doing this by scanning the string "paint". However, it doesn't seem to work -

```
#include <stdio.h>
int main() {
char name[100];
scanf("%s", name);
printf("The name is %c", name[5]);
}

```

This is my output -
```
paint

The name is some weird symbol looking like 0

Process finished with exit code 0

```

Top answer
1 of 2
10

Short Answer:

const char *get_string() { return ""; }

or

char *get_string() { return const_cast<char *>(""); }

or

char *get_string() { return NULL; }

or

std::string get_string() { return std::string(); }


Detailed Answer:

Implicit conversion from string literal to char * is supported in C and C++98/C++03, but apparently not in C++11. The deprecation warning is just there to let you know that this should be addressed, particularly if you want to be able to migrate your code C++11.

The empty string literal ("") is not actually empty, it is a string containing a single null character (\0). When you use return "";, you are actually returning a pointer to the memory location of the const string literal so the function return type should be const char *.

If you really must return a non-const pointer to a string literal, you can use the const_cast operator to cast away the const.

A better practice would be to return NULL (or nullptr) for functions that are returning empty, non-const, C-style strings, but only if the calling code is checking for NULL pointers.

Note that C++ has its own string type (std::string), and an even better practice would be to use this rather than a C-style string when possible.

2 of 2
2
char* foo()
{
    static char empty[1];
    return empty;
}

Just be aware that this function is absolutely stupid, and whatever your actual problem is, this is not likely the correct solution. But, since you refuse to expound upon your actual problem, here you go.

🌐
C For Dummies
c-for-dummies.com › blog
Null Versus Empty Strings | C For Dummies Blog
August 12, 2017 - The string is empty. The strlen() returns an unpredictable value for the null[] array because it’s not initialized. Therefore the string length is wherever the next random null character is found in memory.
🌐
Stack Overflow
stackoverflow.com › questions › 53162316 › c-string-returns-as-null
arrays - C - String returns as NULL - Stack Overflow
November 6, 2018 - char * remove_chars(char s1[], int k, int l) { int j = 0; if(string_length(s1) + 1 < k || string_length(s1) + 1 < l) return 0; else { char s2[100]; for(int i = 0; s1[i] != '\0'; ++i) { if((i <= k - 1) || (i > k + l - 1 )) { s2[j] = s1[i]; ++j; } } s2[j] = '\0'; return s2; } } The problem is, that after I call the remove_chars function in main, it returns as null, but when I try to print s2 inside remove_chars function, it prints it out just like it was supposed to be.
🌐
Quora
quora.com › Is-it-legal-in-C-C-to-return-NULL
Is it legal in C/C++ to 'return NULL'? - Quora
Answer (1 of 21): There is no such thing like “C/C++”. return NULL is legal in C and it usually means, by convention, that something went wrong, e.g. an allocation, and the calling context is supposed to handle the error.