Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "control reaches end of non-void function" mean?

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; } 
like image 548
tekknolagi Avatar asked May 30 '11 01:05

tekknolagi


People also ask

How do I fix error control reaches end of non-void function?

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.

What does control may reach end of non-void function?

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.

What is a non-void function?

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.

How do you end a void function?

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.


2 Answers

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.

like image 65
rid Avatar answered Oct 12 '22 22:10

rid


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;"

like image 23
Ernest Friedman-Hill Avatar answered Oct 12 '22 22:10

Ernest Friedman-Hill