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;
}
detly
29.4k18 gold badges93 silver badges153 bronze badges
asked May 30, 2011 at 1:14
tekknolagitekknolagi
10.7k24 gold badges75 silver badges119 bronze badges
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.
answered May 30, 2011 at 1:16
4
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;«
answered May 30, 2011 at 1:17
4
If the function is non-void,it means it has to return something before reaching the end of function block[ _} ].So, when we give only if and else-if statements the compiler cannot tell from that code,that any of these statements will be evaluated to true and return something.Means, if all of the condition evaluates to false,then the control will reach the end of function,without returning something,which is wrong.
answered Mar 30, 2021 at 12:38
Always build with at least minimal optimization. With -O0, all analysis that the compiler could use to determine that execution cannot reach the end of the function has been disabled. This is why you’re seeing the warning. The only time you should ever use -O0 is for step-by-line debugging, which is usually not a good debugging approach anyway, but it’s what most people who got started with MSVC learned on…
answered May 30, 2011 at 2:26
3
I had the same problem. My code below didn’t work, but when I replaced the last «if» with «else», it works. The error was: may reach end of non-void function.
int shifted(char key_letter)
{
if(isupper(key_letter))
{
return key_letter - 'A';
}
if(islower(key_letter) //<----------- doesn't work, replace with else
{
return key_letter - 'a';
}
}
answered Jan 6, 2014 at 5:23
ThuyThuy
1,4931 gold badge11 silver badges11 bronze badges
Make sure that your code is returning a value of given return-type irrespective of conditional statements
This code snippet was showing the same error
int search(char arr[], int start, int end, char value)
{
int i;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
return i;
}
}
This is the working code after little changes
int search(char arr[], int start, int end, char value)
{
int i;
int index=-1;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
index=i;
}
return index;
}
answered Oct 24, 2020 at 13:11
It means it’s searching for a function that needs to be completed.
else if(val == sorted[mid]) return mid;
so, remove the if() part and modify the code or add an else() at the end which returns an int.
answered Nov 7, 2020 at 10:22
Compiler by itself would not know that the conditions you have given are optimum .. meaning of this is you have covered all cases ..
So therefore it always wants a return statement … So either you can change last else if with else or just write return 0 after last else if ;`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;
return 0; }`
answered Feb 4, 2021 at 12:39
If it’s «main» function just make sure to return 0 or change it from
int main()
to
void main()
answered Apr 26, 2022 at 8:55
NivNiv
8701 gold badge8 silver badges22 bronze badges
Add the binary function to the end of the code:
int binary(int val, int sorted[], int low, int high)
{ /* ... */ return 1;}
If not one of the conditions is not met, the int function should return int.
user16217248
3,19421 gold badges19 silver badges37 bronze badges
answered May 13 at 7:23
add to your code:
"#include < stdlib.h>"
return EXIT_SUCCESS;
at the end of main()
Ram Sharma
8,6767 gold badges44 silver badges56 bronze badges
answered Jan 9, 2015 at 11:59
2
|
maytreya 0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
||||
|
1 |
||||
|
21.02.2021, 11:22. Показов 32404. Ответов 19 Метки нет (Все метки)
Добрый день, коллеги. Продолжаю решать задачки с целью подготовки к экзамену. Задачу про НОД решил попробовать двумя способами. И если первый вариант я подсмотрел теорию за .. какой то там класс, то второй — это, так сказать, мысли мои и не самые удачные, видимо. Короче …. при запуске второго варианта VS выдает » cpp:72:1: warning: control reaches end of non-void function [-Wreturn-type]
Добавлено через 3 минуты
0 |
|
Диссидент 27682 / 17305 / 3806 Регистрация: 24.12.2010 Сообщений: 38,960 |
|
|
21.02.2021, 11:50 |
2 |
|
cpp:72:1: warning: control reaches end of non-void function [-Wreturn-type] Ерунда. Предупреждение. Функция должна что-то возвращать. Поставь в строчку 71 return 0; Или Добавлено через 2 минуты
1 |
|
0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
|
|
21.02.2021, 13:10 [ТС] |
3 |
|
………. delitel (m,n,x-1, i+1);
0 |
|
oleg-m1973 6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
||||
|
21.02.2021, 13:46 |
4 |
|||
|
Вот так? но тогда ответ k=0 всегда.
0 |
|
Диссидент 27682 / 17305 / 3806 Регистрация: 24.12.2010 Сообщений: 38,960 |
|
|
21.02.2021, 15:18 |
5 |
|
maytreya, все мои замечания касается только твоего
cpp:72:1: warning: control reaches end of non-void function [-Wreturn-type] Про ответ ничего не знаю, это отдельно смотреть…
0 |
|
maytreya 0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
||||
|
21.02.2021, 23:27 [ТС] |
6 |
|||
|
Спасибо за подсказку. Нашел еще одну логическую нестыковку, попробую добить до рабочего состояния)). Добавлено через 3 часа 5 минут
0 |
|
6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
|
21.02.2021, 23:29 |
7 |
|
//считает верно, но постоянно выдает предупреждение. Не могу понять почему. Я ж тебе вроде показал, что нужно сделать
int delitel (int m, int n, int x, int i)
0 |
|
0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
|
|
21.02.2021, 23:33 [ТС] |
8 |
|
Кстати, не рискнул выделить в отдельную тему. Подскажите где можно узнать о правильном написании кода, а то мне тут давеча намекнули, что мол пишу коряво))) Добавлено через 2 минуты
Я ж тебе вроде показал, что нужно сделать Я так делал… в результате всегда 0(ноль)
0 |
|
2441 / 1839 / 406 Регистрация: 15.12.2013 Сообщений: 8,218 |
|
|
21.02.2021, 23:33 |
9 |
|
Больше пишите и больше читайте, вот и весь секрет.
0 |
|
6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
|
21.02.2021, 23:34 |
10 |
|
Я так делал… в результате всегда 0(ноль) Покажи, как делал
0 |
|
maytreya 0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
||||
|
21.02.2021, 23:36 [ТС] |
11 |
|||
0 |
|
6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
|
21.02.2021, 23:38 |
12 |
|
if (m%x==0 && n%x==0) Твоя проблема не в том, что ты коряво пишешь, а в том, что не слушаешь, то что тебе говорят. Корявый код — это следствие.
0 |
|
0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
|
|
21.02.2021, 23:39 [ТС] |
13 |
|
Покажи, как делал 78 строчка
0 |
|
6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
|
21.02.2021, 23:40 |
14 |
|
Жирным пометил, на случай, если ты цвета не различаешь Добавлено через 56 секунд
78 строчка return delitel (m,n,x-1) сделал?
0 |
|
0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
|
|
21.02.2021, 23:44 [ТС] |
15 |
|
return delitel (m,n,x-1) сделал? да… опять ноль Добавлено через 2 минуты
0 |
|
oleg-m1973 6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
||||
|
21.02.2021, 23:46 |
16 |
|||
|
да… опять ноль Да ладно
Добавлено через 1 минуту
вот когда убираю «return 0; » тогда считает правильно, но опять предупреждение Ты лучше показывай как сделал, а то большие сомнения в твоих словах.
0 |
|
maytreya 0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
||||
|
21.02.2021, 23:49 [ТС] |
17 |
|||
|
Весь код не передаю только концовку
Добавлено через 57 секунд
0 |
|
6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
|
21.02.2021, 23:51 |
18 |
|
Весь код не передаю только концовку return 0 в конце добавь и всё будет правильно. Добавлено через 23 секунды
return 0; если на 13 строке, то ответ ноль При каких параметрах? Добавлено через 1 минуту
1 |
|
0 / 0 / 0 Регистрация: 05.02.2021 Сообщений: 28 |
|
|
22.02.2021, 00:00 [ТС] |
19 |
|
Сделай return 1. Это когда общего делителя нет ух ты… получилось. теперь бы понять почему….Спасибо огромное … буду разбираться))) Добавлено через 4 минуты
0 |
|
6578 / 4563 / 1843 Регистрация: 07.05.2019 Сообщений: 13,726 |
|
|
22.02.2021, 00:06 |
20 |
|
еще раз спасибо… все понял Для спасибо есть специальная кнопка
3 |
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;
}
detly
29.4k18 gold badges93 silver badges153 bronze badges
asked May 30, 2011 at 1:14
tekknolagitekknolagi
10.7k24 gold badges75 silver badges119 bronze badges
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.
answered May 30, 2011 at 1:16
4
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;«
answered May 30, 2011 at 1:17
4
If the function is non-void,it means it has to return something before reaching the end of function block[ _} ].So, when we give only if and else-if statements the compiler cannot tell from that code,that any of these statements will be evaluated to true and return something.Means, if all of the condition evaluates to false,then the control will reach the end of function,without returning something,which is wrong.
answered Mar 30, 2021 at 12:38
Always build with at least minimal optimization. With -O0, all analysis that the compiler could use to determine that execution cannot reach the end of the function has been disabled. This is why you’re seeing the warning. The only time you should ever use -O0 is for step-by-line debugging, which is usually not a good debugging approach anyway, but it’s what most people who got started with MSVC learned on…
answered May 30, 2011 at 2:26
3
I had the same problem. My code below didn’t work, but when I replaced the last «if» with «else», it works. The error was: may reach end of non-void function.
int shifted(char key_letter)
{
if(isupper(key_letter))
{
return key_letter - 'A';
}
if(islower(key_letter) //<----------- doesn't work, replace with else
{
return key_letter - 'a';
}
}
answered Jan 6, 2014 at 5:23
ThuyThuy
1,4931 gold badge11 silver badges11 bronze badges
Make sure that your code is returning a value of given return-type irrespective of conditional statements
This code snippet was showing the same error
int search(char arr[], int start, int end, char value)
{
int i;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
return i;
}
}
This is the working code after little changes
int search(char arr[], int start, int end, char value)
{
int i;
int index=-1;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
index=i;
}
return index;
}
answered Oct 24, 2020 at 13:11
It means it’s searching for a function that needs to be completed.
else if(val == sorted[mid]) return mid;
so, remove the if() part and modify the code or add an else() at the end which returns an int.
answered Nov 7, 2020 at 10:22
Compiler by itself would not know that the conditions you have given are optimum .. meaning of this is you have covered all cases ..
So therefore it always wants a return statement … So either you can change last else if with else or just write return 0 after last else if ;`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;
return 0; }`
answered Feb 4, 2021 at 12:39
If it’s «main» function just make sure to return 0 or change it from
int main()
to
void main()
answered Apr 26, 2022 at 8:55
NivNiv
8701 gold badge8 silver badges22 bronze badges
Add the binary function to the end of the code:
int binary(int val, int sorted[], int low, int high)
{ /* ... */ return 1;}
If not one of the conditions is not met, the int function should return int.
user16217248
3,19421 gold badges19 silver badges37 bronze badges
answered May 13 at 7:23
add to your code:
"#include < stdlib.h>"
return EXIT_SUCCESS;
at the end of main()
Ram Sharma
8,6767 gold badges44 silver badges56 bronze badges
answered Jan 9, 2015 at 11:59
2
Hello everyone, In this article, we are going to discuss a common problem faced by beginners and also experienced programmers. Often when we run into the warning saying warning: control reaches end of non-void function. Generally, we ignore this error because most of the time as the program still runs the same even if this warning is coming.
Let’s first see a simple example then this kind of error can occur.
|
#include <bits/stdc++.h> using namespace std; int fun(){ if(false) return 0; } // Error here int main() { fun(); return 0; } |
If we run this c++ code it works fine and terminates but we get an error at the 8th line saying control reaches end of non-void function.
To understand this error we first have to understand the working of the compiler a bit in detail. There are two important kinds of error which occurs while running a program.
Compile-time error: Error which can be identified by the compiler without running the program. Generally, these are syntax error which is identified without running the program.
Run-time error: Error which occurs when the program syntax is correct but there is some problem while the program is run. Generally invalid memory access, infinite loops fall under runtime error.
Every function has a return type which states the type of value the function will be returning. If the function is not going to return any value it is given a void return type, Any other return valued function is a non-void function.
We get the above error when the non-void function is not returning any value.
In the above example the if condition is always false and therefore it will reach the end of the function without returning anything and that’s why we are getting the warning message. Control in the warning message means the flow of the program.
Now coming to the runtime and compile-time error part, the message which we are getting here is identified at compile time using just the syntax of the program and the program is not actually run to check if it is reaching the end of any non-void function.
Let’s take the below example:
|
#include <bits/stdc++.h> using namespace std; int fun(int x){ if(x < 5) return 0; } // line 8 int main() { fun(4); return 0; } |
In this example, we are always sure that if we run the program it will return the values 0, but still we will get the same warning message because the compiler is not smart enough to understand at compile-time that when this program is run it will always return value. The compiler is just checking the syntax and it interprets that for the function fun if the if condition is false, the flow of the program will reach line 8 and it won’t be returning any value and therefore we get the error.
Sometimes it may be the case that we have several if-else if statements with return value which cover all the conditions but if there is no else statement we will still get the error because the compiler could not understand that all the conditions are covered.
How to Solve?
There is an easy solution to the problem, even if we understand that every condition is covered we should add a return statement at the end of the function so the compiler is sure that the non-void function will be returning some value. It may happen that flow is never reaching that part of the code but it is important to write for the compiler.
|
#include <bits/stdc++.h> using namespace std; int fun(int x){ if(x < 5) return 0; return 1; // line 8 } int main() { fun(4); return 0; } |
The above code will not give any warning and the flow also won’t go to line 8 but still, it’s important to have the return statement there.
It’s a good practice to avoid this warning, many times code will run just fine even if warning is coming but for some cases, it may cause wrong behaviour of code, to avoid that its good practice to avoid this warning.
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. At this time, it is good to take a look at whether or not every control flow contains a return value. To recognize this fault, we first must recognize the working of the compiler.
There are two varieties of inaccuracies that happen whilst executing a program.
Compile-time errors: Fault which may be recognized with the aid of using the compiler without executing the code. Usually, those are syntax mistakes that are recognized without executing the code.
Run-time errors: Fault which happens while the program syntax is accurate; however, there’s a little trouble whilst the code is executing. Usually, invalid reminiscence access limitless loops fall below runtime mistakes.
This article will speak about common trouble confronted by novices and additionally skilled programmers. We often execute into the caution stating caution: ‘control reaches the end of non-void function’. Usually, we neglect this error due to the fact maximum of the time because the program nevertheless executes the same, even supposing this caution is coming.
Get the warning message:
Compiling this code executes, but an error occurs, which shows the warning ‘control reaches the end of non-void function’. Each function contains a return type that shows the kind of value the function maybe return. If the method isn’t returning any value, it’s far from a void return type. We obtain the above error, while the non-void function doesn’t return the value.
#include <bits/stdc++.h>
using namespace std;
int f(){
if(false)
return 0;
}
int main() {
f();
return 0;
}
In this case, first, we integrate the header file and use the namespace standard. Further, we apply the if statement. Sometimes it can be the situation that we’ve numerous if-else if statements and all the statements contain the return value; however, if there’s no else assertion, we can nevertheless get the error due to the fact the compiler couldn’t comprehend that every situation is covered.
Here we get nothing in output, so it means the code is executed successfully, but the function doesn’t return any value.
Use If statement:
In this instance, if the condition is usually not true and consequently it’ll stop the function ‘f’ deprived of returning some value. And it is the reason behind receiving the attention message. Control within the attention message shows the flow of this code. Now let’s check whether it is a runtime error or compile-time error. The warning which we obtain right here is detected at assemble time, the use of simply the syntax of this code and the code isn’t always definitely executed to test if it’s far achieving the termination of any non-void method.
#include <bits/stdc++.h>
using namespace std;
int f(int a){
if(a < 8)
return 0;
}
int main() {
f(3);
return 0;
}
We are always assured that if we execute the code, it is returning 0 value; however, nevertheless, we can obtain the same caution message due to the fact the compiler isn’t working smartly enough to recognize at compile-time that once this code is executed, it’s going to return the value each time. The compiler simply checks the syntax of the code, and it translates that for the function ‘f’ if the defined condition is not true, the flow of this code will attain line eight, and it couldn’t return the value, and hence we obtain the mistake.
After compiling the program, in output, we get nothing due to the error ‘control reaches the end of non-void function’.
Use the return statements:
When the conditional statements must not include any return statements, the control gets to the end of a non-void function in another way. Therefore, if the implementation within the non-void method is separated and if statements couldn’t execute each path, then at the end, we have to explicitly call ‘return’ for the function.
The subsequent instance validates the string handling function having conditional paths. Here we include three libraries for different purposes, and after that, we declare a function. On the other hand, a few instances are left now no longer assessed for the defined condition, which means that control flow may attain the cease of the function and produce errors.
Here we defined the function ‘reversestring’. We pass the string and condition as parameters to this function. The function body contains no return statement. However, it contains no arguments to call the function. So the compiler just shows the caution message. If we call the function, then we don’t get the error.
Conclusion:
In this article, we get information about the error: ‘control reaches the end of non-void function’ and see how we get this error. The non-void method contains the return type. Thus, the method wants to have a declaration that returns the items of the resultant type. If definite compiler standards are accepted, this error may get repressed completely, leading to run-time errors if the specified method calls in the code.
About the author

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.








