I've been getting strange compiler errors on this binary search algorithm. I get a warning that control reaches end of non-void function
. What does this mean?
int binary(int val, int sorted[], int low, int high) { int mid = (low+high)/2; if(high < low) return -1; if(val < sorted[mid]) return binary(val, sorted, low, mid-1); else if(val > sorted[mid]) return binary(val, sorted, mid+1, high); else if(val == sorted[mid]) return mid; }
If control reaches the end of a function and no return is encountered, GCC assumes a return with no return value. However, for this, the function requires a return value. At the end of the function, add a return statement that returns a suitable return value, even if control never reaches there.
When we write the programs in C++. After executing programs, sometimes we get the error: 'warning: control reaches the end of non-void function', which means that certain functions that would have to return some values attain the termination. It might not give any value later.
Functions that return are great for when we need to go through a lot of steps to get a value that we want to use in our code somewhere. Calling a non-void function tells the computer to head over to the function definition, do everything, and come back with the result once it's done.
1) A Void Function Can Return: We can simply write a return statement in a void fun(). In fact, it is considered a good practice (for readability of code) to write a return; statement to indicate the end of the function.
The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...)
with just else
.
The compiler isn't smart enough to know that <
, >
, and ==
are a "complete set". You can let it know that by removing the condition "if(val == sorted[mid])" -- it's redundant. Jut say "else return mid;
"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With