Reputation: 1
I have this modefied binary search function that finds the lowest( the value that is closest to L - a known value) and the highest value in a vector(the value that is closest to R - the same known value). Unfortunatelty, when I try to compile the code I get this warning and I dont know why: control reaches end of non-void function.
int bs_counts (vector <int> Arr, int x, int low, int high, bool searchDirection)
{
bool done = false;
int new_middle = 0;
int mid = (low + high)/2;
while(low <= high && done == true)
{
if(Arr[mid] == x)
{
new_middle = mid;
done = true;
}
else if(Arr[mid] > x)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
if(done == true)
{
return new_middle;
}
else
{
if(searchDirection == true)
{
return low;
}
else if (searchDirection == false)
{
return high;
}
}
}
Upvotes: 0
Views: 3420
Reputation: 2850
1st of all, please format your code properly, as it looks like the 3 return
statements are inside the while
loop, which isn't the case.
The compiler is confused, look at this fragment of code.
if (done == true)
{
return new_middle;
}
else
{
if (searchDirection == true)
{
return low;
}
else if (searchDirection == false)
{
return high;
}
}
We can obviously see that searchDirection
will be either true
or false
, and something will always be returned, but the compiler might be overlooking that, change it to the following.
if (done == true)
{
return new_middle;
}
else
{
if (searchDirection == true)
{
return low;
}
else
{
return high;
}
}
And the warning disappeared.
Upvotes: 2