0

I have written my binary search code, but every time i try to compile I get the following error

jharvard@appliance (~/Dropbox/pset3/find): make helpers
clang -ggdb3 -O0 -std=c99 -Wall -Werror    helpers.c  -lcs50 -lm -o helpers
helpers.c:49:1: error: control may reach end of non-void function [-Werror,-Wreturn-type]
}
^
1 error generated.
make: *** [helpers] Error 1

Here is my code:

bool search (int value, int values[], int n)

{

    if (n > 0)
    {
        int min = 0, max = n-1;
        while (n > 0)
        {
            int mid = ((min + max)/2);

            if (value == values[mid])
            {
                return true;
            }

            else if (value < values[mid])
            {
                max = mid - 1;
                continue;
            }

            else
            {
                min = mid + 1;
                continue;
            }
            return false;

        }
    }

    else
    return false;
}

Can you explain what's wrong?

2 Answers 2

1

That means that the function could reach a point, that it would have to return, but there is nothing that it can return. In your case it is, if it passes your first if but not the while. You and I and every human knows that if n > 0 in if is true, it's going to be true to the while too. But the compiler doesn't know that. There are some logic mistakes in your code too that might cause a infinite loop. Also see that question: How to solve "control may reach end of non void function" error

0

You don't need to add else at the last line bc its a bool return . just add return false. Until your function come to that line it has to return true and bool returns. if it cant find the value, return has to be false. So leave return false alone.

1
  • but it shouldn't make any difference.
    – Andrej
    Nov 21, 2015 at 5:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .