Search code examples
c++return-valuecompiler-warningssuppress-warnings

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


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.


Solution

  • 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;
    }