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.

Answer from Adem on Stack Overflow
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 ...
  }
}
Discussions

Should I return null or an empty object?
That depends on whether you consider not finding the file an error - then return null - or if you want to have a list of all nodes matching your pattern no matter whether a file exists - then return an empty object. More on reddit.com
🌐 r/AskProgramming
16
9
July 25, 2023
c# - Should functions return null or an empty object? - Stack Overflow
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. What is the best practice when returning data from functions. Is it better to return a Null or an empty object? More on stackoverflow.com
🌐 stackoverflow.com
object oriented - Is it better to return NULL or empty values from functions/methods where the return value is not present? - Software Engineering Stack Exchange
Also, this way, the caller would not have to check to see if a NULL was returned. In FindPerson(), returning NULL seems like a better fit. Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 17, 2011
Best Practice: Should functions return null or an empty object? - Stack Overflow
Anyone else think that r/coding should try to keep the stack overflow links to a minimum? More on reddit.com
🌐 r/coding
68
64
October 28, 2009
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › c › MSC19-C.+For+functions+that+return+an+array,+prefer+returning+an+empty+array+over+a+null+value
MSC19-C. For functions that return an array, prefer returning an empty array over a null value - SEI CERT C Coding Standard - Confluence
This compliant solution correctly returns an empty array in the sortedArray function. If the size of the array is 0, then sortedArray allocates an array of size 1 and fills it with the sentinel value. It can then successfully return that array to the caller function.
🌐
Coderanch
coderanch.com › t › 99773 › engineering › Null-Empty-object-Return-Type
Null or Empty object (Return Type) (OO, Patterns, UML and Refactoring forum at Coderanch)
I really don't like the idea of returning either String[] or null. If the account does not exist, then I'd throw a FinderException or something similar for the client to handle. Isn't this what exceptions are for? But if the object was instantiated on a remote machine (via RMI or whatever), the extra round trip to free an empty String array object (that provided no information that a null return value couldn't have) may incur some non-trivial overhead.
🌐
Reddit
reddit.com › r/askprogramming › should i return null or an empty object?
r/AskProgramming on Reddit: Should I return null or an empty object?
July 25, 2023 -

My company uses files that are essentially merged XML files into one. I wrote a pretty basic parser and node object that contains the tag name, text, and child node objects. Recently I ran into an error where the file couldn't be found, and my function that searches for child nodes returned null (as it should). But it caused a runtime error, so I'm trying to figure out the best way to address issue. Should I return an empty object so that the code doesn't crash, or should I continue returning null and wrap it in a try/catch?

Top answer
1 of 16
206

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.

2 of 16
44

It depends on what makes the most sense for your case.

Does it make sense to return null, e.g. "no such user exists"?

Or does it make sense to create a default user? This makes the most sense when you can safely assume that if a user DOESN'T exist, the calling code intends for one to exist when they ask for it.

Or does it make sense to throw an exception (a la "FileNotFound") if the calling code is demanding a user with an invalid ID?

However - from a separation of concerns/SRP standpoint, the first two are more correct. And technically the first is the most correct (but only by a hair) - GetUserById should only be responsible for one thing - getting the user. Handling its own "user does not exist" case by returning something else could be a violation of SRP. Separating into a different check - bool DoesUserExist(id) would be appropriate if you do choose to throw an exception.

Based on extensive comments below: if this is an API-level design question, this method could be analogous to "OpenFile" or "ReadEntireFile". We are "opening" a user from some repository and hydrating the object from the resultant data. An exception could be appropriate in this case. It might not be, but it could be.

All approaches are acceptable - it just depends, based on the larger context of the API/application.

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.

🌐
Reddit
reddit.com › r/coding › best practice: should functions return null or an empty object? - stack overflow
r/coding on Reddit: Best Practice: Should functions return null or an empty object? - Stack Overflow
October 28, 2009 - Sometimes they aren't failures, though - you may not always want to have an xyz in your class by default (set it to nil in init) - passing it around won't break the bank, but won't cause the out-of-the-ordinary to happen either. ... My general rule when it comes to this is, to return null. Only return an empty object when there is a reason not to return null :)
Find elsewhere
Top answer
1 of 3
2

Not exactly the same, but you can get your string as a function parameter instead of as a return value and rely on the fact that temporaries bind to const references.
As an example:

#include <string>
#include <iostream>
#include <utility>

struct S {
    template<typename F>
    void get(bool b, F &&f) {
        std::forward<F>(f)(b ? s : "");
    }

    std::string s{"foo"};
};

int main() {
    S s;
    s.get(true,  { std::cout << str << std::endl; });
    s.get(false,  { std::cout << str << std::endl; });
}

This can be a valid alternative if libraries like Boost are not already part of your project and you don't want to include them.


Otherwise, as others have mentioned, you can pick up an upcoming utility called std::optional and combine it with std::reference_wrapper as it follows:

#include <string>
#include <iostream>
#include <experimental/optional>
#include <functional>

struct S {
    std::experimental::optional<std::reference_wrapper<std::string>> get(bool b) {
        return b ? std::ref(s) : std::experimental::optional<std::reference_wrapper<std::string>>{};
    }

    std::string s{"foo"};
};

int main() {
    S s;

    auto opt1 = s.get(true);
    std::cout << (opt1 ? opt1->get() : "-") << std::endl;

    auto opt2 = s.get(false);
    std::cout << (opt2 ? opt2->get() : "-") << std::endl;
}

Pretty ugly indeed. Note that a std::optional should be verified through its operator bool or the member method has_value to be sure that it contains a value.

Unfortunately you cannot use directly a std::reference_wrapper as return value, for it cannot be (let me say) _empty). In other terms, if you want to construct such an object, you must pass a valid reference to its constructor.


Another approach would be by using a template class like the following one:

#include <string>
#include <type_traits>
#include <iostream>

template<typename T>
struct defval {
    static const std::decay_t<T> value;
};

template<typename T>
const std::decay_t<T> defval<T>::value = T{};

struct S {  
    const std::string & get(bool b) {
        return b ? str : defval<std::string>::value;
    }

    std::string str{"foo"};
};

int main() {
    S s;
    std::cout << s.get(true) << std::endl;
    std::cout << s.get(false) << std::endl;
}

Note that you must specialize it for those types that are not default constructible.

2 of 3
0

References must be bound to an object. So you can't return a reference in your case. Your options are:

  1. Return a (non-owning) pointer.
  2. Return something like boost::optional, which can hold a reference (unlike the soon to be added std::optional).
🌐
Reddit
reddit.com › r/codinghelp › create empty object when there is no empty constructor?
r/CodingHelp on Reddit: Create empty object when there is no empty constructor?
September 28, 2023 -

Any C-based language would help with this question. Doing some LeetCode and I need to return an empty list object but there is no option for an empty constructor, in fact it automatically adds a 0 value once instantiated. I looked at a few different languages and they all seem to do the same thing. Here's the class definition:

* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }

Empty ListNode objects can be given to the method, as stated in the constraints section. I'm currently just returning one of those for the edge case, but how could I possibly make my own?

🌐
The Coding Forums
thecodingforums.com › archive › archive › c++
function returning reference to empty object | C++ | Coding Forums
May 18, 2007 - Your class can have a static instance of itself, something like class MyClass { public: ... static MyClassData errorVariable; }; .... MyClassData MyClass::errorVariable; .... if (data are ok) return data; else return errorVariable; .... if (&returnValueFromFunction == &errorVariable) But it's better to 'try-catch' and 'throw'. V ... Dear All, can someone clarify me how to return the reference to the empty object in case of error?
🌐
MethodPoet
methodpoet.com › return-null-or-empty-value
3 Clever Ways to Return Empty Value Instead of Null From a Method | MethodPoet
December 29, 2022 - Otherwise, the code throws exceptions. Several alternatives for returning null values include using null object reference types, a null object pattern, and a result type as the return type. Therefore, the recommendation is to return an empty value instead of a null to keep the code clean and error-free.
🌐
Cplusplus
cplusplus.com › reference › array › array › empty
std::array::empty
Returns a bool value indicating whether the array container is empty, i.e. whether its size is 0. This function does not modify the content of the array in any way. To clear the content of an array object, use array::fill.
🌐
Reddit
reddit.com › r/csharp › is it better to return null or a new object?
r/csharp on Reddit: Is it better to return null or a new object?
December 26, 2022 -

Always wondered this. If you have a scenario where an object might not have a value for example I don't know a query from a database should you...

  • Return null and handle that client side

  • Return a new empty list or object of whatever class the method returns and then handle it client side

  • Throw an exception

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.

🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › how-to-return-empty-char-*-750700
How to return empty char * ?
August 27, 2009 - Hi: Here is my code: Code: char * func1(){ ... ... return ""; } This code give me warning "deprecated convertion from string to char *
🌐
Cplusplus
cplusplus.com › reference › string › string › empty
std::string::empty
Returns whether the string is empty (i.e. whether its length is 0). This function does not modify the value of the string in any way. To clear the content of a string, see string::clear. ... This program reads the user input line by line and stores it into string content until an empty line is introduced. Unspecified, but generally constant. ... No changes. The object is accessed.
🌐
Studiofreya
studiofreya.com › programming-basics › return-empty-objects-not-nulls
Return empty objects, not nulls | Studio Freya
November 19, 2019 - The result of such code in cases where the person cannot be found is Server error. So, there is no reason ever to return null from an object-valued method instead of returning an empty object.