Reputation: 461
I have looked through this function over and over and cannot figure out why I am getting this warning/error when trying to compile the code. The compiler I use runs with -Werror so I am not sure if it is a warning or an error, but the error I am getting is:
error: control may reach end of non-void function [-Werror,-Wreturn-type]
Here is my function
int binarySearch(int key, int array[], int min, int max)
{
//Check if there is value is not found
if(max < min)
{
return -1;
}
else
{
//find midpoint
int midpoint = (min + max) / 2;
//Run recursive steps
if(array[midpoint] < key)
{
binarySearch(key, array, midpoint + 1, max);
}
else if(array[midpoint] > key)
{
binarySearch(key, array, min, midpoint - 1);
}
else
{
return midpoint;
}
}
}
Upvotes: 0
Views: 173
Reputation: 1973
If array[midpoint] < key
or array[midpoint] > key
, you call binarySearch
recursively and then fall off the end of the function without specifying a return value. You presumably want to return the value returned by the recursive calls in those two branches, e.g.
return binarySearch(key, array, midpoint + 1, max);
(To answer your other question, the compiler diagnostic would have been a warning if -Werror
wasn't set, but the warning indicates a bug in the code, which is of course why -Werror
is generally a good idea.)
Upvotes: 2