سؤال

I am not able to compile my code, I am getting error: control may reach the end of a non-void function

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    //Binary search algorithm
    int first = 0;
    int last = n-1;
    int middle = (first+last)/2;

    if (n<1)
        return false;
    else
    {
        while (first <= last)
        {
            if (values[middle]==value)
                return true;
            else if(values[middle]<value)
                first=middle+1;
            else if (values[middle]>value)
            {
                last=middle-1; 
            }
            middle=(first+last)/2;
        }
    }

    if (first>last)
        return false;
}

Can anyone look through my code and help me figure out where the issue is? I am struggling to see it myself! From my point of view, this function returns true or false

هل كانت مفيدة؟

المحلول 2

In your code it's not possible for the function to fall off the end.

However, the compiler is not required to accurately diagnose whether a function can get to the end or not. In general, to do so would require solving the halting problem.

Instead, as a practical measure, your compiler is doing some basic checks and warning because it sees the if ( first > last ) return false;, it didn't do enough code analysis to determine that this branch can never be reached unless first > last.

To suppress this warning you could just remove the line if ( first > last ). BTW this is a warning, not an error; so it should not prevent your compilation.

نصائح أخرى

Your return type of bool means that your function is always expected to return a boolean value before it exits, no matter which path of execution it takes. As it stands now, it appears on inspection that you can "fall through" the last if and never hit a return statement. To verify otherwise would require stepping through your logic in a way the compiler cannot reasonably be expected to do. At the end simply change to say:

  if (first>last) {
      return false;
  } else {
      return true;
  }

Or more concisely:

 return (first > last) ? false : true;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top