6

I have a struct like this

struct AUTO{
   int weight;
   string name;
}

and I have a function that return a struct by passing name

AUTO autoByName(String name, AUTO a[], int ll)
{
   for(int i = 0; i < ll; i++)
   {
      if (name == a[i].name)
      {
         return a[i];
      }
   }

   // AND HERE ?????
}

but I don't know what return at the end of the function. Is there a null for struct ?

Fry
  • 6,235
  • 8
  • 54
  • 93
  • 3
    No. You would have to engineer some value that represents a null `AUTO`, or return some kind of optional object that can be tested (see `boost::optional` for example.) – juanchopanza Apr 09 '14 at 19:33
  • @juanchopanza: You should post that as an answer. – Keith Thompson Apr 09 '14 at 19:34
  • 2
    There are many options: return a pointer (and nullptr is a valid return), throw an exception, return a bool and return the value via a reference parameter, have a "sentinel" value indicating a non-valid `AUTO`... – crashmstr Apr 09 '14 at 19:35
  • @KeithThompson I am looking for good duplicates. There are plenty out there, but so far I have only found ones with poor answers. – juanchopanza Apr 09 '14 at 19:37
  • It makes no sense for a struct instance to be null. This isn't Java where most everything is a reference to an object. – Ed S. Apr 09 '14 at 19:38

1 Answers1

6

You have a lot of options:

  1. Give AUTO a way to represent a "no-value". For example by making weight -1. Or by adding a flag to it. This is pretty ugly; I don't recommend it, even though it's somewhat common in practice.
  2. Return a (smart) pointer instead of value. This way you can return a nullptr in the case of error / no value. This is also ugly because it forces you to deal with pointers for not a very good reason.
  3. Return a separate value to indicate success. For example adding a bool &wasFound argument to the function.
  4. Return boost::optional or std::pair<AUTO, bool> to accomplish pretty much the same thing, but all wrapped up in the return value. This is probably the cleanest. This is how std::map::find works, for example.
  5. Throw an exception. It's possible that this is acceptable if callers don't try to find items that don't exist. In other words, if "not found" is just a return value then don't throw an exception. If "not found" is truly a program error condition, throwing an exception may actually make sense. If you're not sure, don't throw an exception.

I'd recommend #4, or in rarer cases #5.

tenfour
  • 36,141
  • 15
  • 83
  • 142
  • To be more explicit choose option #5 if not finding a matching object is an error case. If normally the object might not exist and you need a way to query its existence then choose option #4. – NickC Apr 09 '14 at 19:50