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 OverflowC++ 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 "";
}
}
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:
- throw an exception
- 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.
}
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?
Return empty string in c - Stack Overflow
Returning null instead of empty string if a wrapped function returns null pointer
String NULL? - C++ Forum
How to access the return value of a C function that can return null to return an error?
Videos
It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application.
So, I would return strdup(""), so you can free it safely.
return '\0' is not correct; it is a null character.
return "";
is more correct.
And you can make a small test function to test returning an empty string, before your data structure is implemented.
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.
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.
Your line char *str = '\0'; actually DOES set str to (the equivalent of) NULL. This is because '\0' in C is an integer with value 0, which is a valid null pointer constant. It's extremely obfuscated though :-)
Making str (a pointer to) an empty string is done with str = ""; (or with str = "\0";, which will make str point to an array of two zero bytes).
Note: do not confuse your declaration with the statement in line 3 here
char *str;
/* ... allocate storage for str here ... */
*str = '\0'; /* Same as *str = 0; */
which does something entirely different: it sets the first character of the string that str points to to a zero byte, effectively making str point to the empty string.
Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings. Pointers, however, are the only objects in C that can be NULL. And don't confuse the NULL macro with the NUL character :-)
No, in this case you're pointing to a real (non-null) string with a length of 0. You can simply do the following to set it to actual null:
char* str = NULL;
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
```
You can throw an exception to indicate an error.
try {
std::string response = receiveFromServer();
} catch(std::runtime_error & e) {
std::cerr << e.what();
}
Then you would need a throw std::runtime_error("Error receive response") somewhere in receiveFromServer().
It is often considered good practice (though some might disagree) to create your own exception-classes that derive from std::runtime_error to enable clients to catch your errors specifically.
You can either throw an exception (better way), or return boost::optional< string >, but then you have to check if the return value is valid (this is actually worse).
if( mystruct == NULL )
mystruct is not a pointer, so you cannot compare it with NULL.
You have three options:
- Add a status field to
MyStructto indicate whether the struct has been initialized correctly. - Allocate the struct on the heap and return it by pointer.
- Pass the structure as a pointer argument and return a status code (thanks @Potatoswatter).
A structure is not a pointer. If you want to be able to return NULL, you're going to have to allocate the structure on the heap so you can return a pointer to it, and let the caller clean up afterwards.
That way, you can indicate failure, something like:
MyStruct *init_mystruct (void) {
MyStruct *mystruct = malloc (sizeof (*mystruct));
if (mystruct != NULL)
return NULL;
int is_ok = 1;
/* do something ... */
/* everything is OK */
if( is_ok )
return mystruct;
/* something went wrong */
free (mystruct);
return NULL;
}
int main (void) {
MyStruct *mystruct = init_mystruct();
if (mystruct == NULL) {
/* error handler */
return -1;
}
free (mystruct);
return 0;
}
If the return type is int, you can't return a NULL. To show an error, you could instead return a special value like zero or -1, if you check for that value in any calling function. Lots of functions return nonnegative numbers on success, or -1 on error.
NULL cannot be stored in an int variable, unlike in SQL, for example. If you ignore the warning and return NULL anyway, then NULL will be casted to zero. The calling function won't be able to tell whether you returned NULL or zero.
If your function only needs to indicate success or failure, then it's common to return 1 for success, and zero for failure. Zero means "false" when treated as a boolean value (like in if statements), and non-zero means "true."
It looks like you've misunderstood what NULL means in C. Types are not nullable. NULL is effectively just a shorthand for the pointer with value 0! And int is not a pointer.