Best way to avoid 'control reaches end of non-void function' warning in release mode

1k views Asked by At

I have a class (here MyObject) with a function returning a name by refererence depending on the internal type of the object. Moreover, this function can only be called for some values of the internal type.

/**
 * \brief Return the name depending of the internal type
 * \pre   The internal type must be 1 or 2
 */
inline
const std::string& MyObject::getName() const
{
  switch(this->type)
  {
    case 1:
      return this->type1->getName();
      break;
    case 2:
      return this->type2->getName();
      break;
    default:
      assert(false && "PRE: Invalid type for this operation");
  }
}

Then, when I compile in Release mode, I get this warning :

warning: control reaches end of non-void function

What is the best way to avoid this warning in this case ? I can't return an empty string, because it will result in a reference to a temporary object, and then another warning. I prefer to not throw an exception in this context, because it's only to solve the warning. If the execution calls the default part, it's a programming bug, it will be detect in Debug mode in pre-prod with the assertion. Normally, the execution never calls it in Release mode, and it's acceptable to have a undefined behaviour in this case.

2

There are 2 answers

2
Thomas Sparber On BEST ANSWER

You can return the reference of a static variable:

/**
 * \brief Return the name depending of the internal type
 * \pre   The internal type must be 1 or 2
 */
inline
const std::string& MyObject::getName() const
{
  switch(this->type)
  {
    case 1:
      return this->type1->getName();
      break;
    case 2:
      return this->type2->getName();
      break;
    default:
      assert(false && "PRE: Invalid type for this operation");
  }

  static std::string hack("");
  return hack;
}
2
Tony Delroy On

"...it's acceptable to have a random behaviour in this case."

It may be acceptable, but why would you want to? Just add an exit(1); after the assert and you wouldn't be spending time on here, or write a macro to add both assert and exit.

Separately, you don't need to break from cases that return.