Control may reach end of non void function что это

Обновлено: 07.07.2024

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?

27.2k 13 13 gold badges 86 86 silver badges 143 143 bronze badges 9,631 21 21 gold badges 69 69 silver badges 113 113 bronze badges

Предупреждение при компиляции "control reaches end of non-void function"

Control reaches end of non-function
Это не ошибка, а предупреждение, компиляция проходит, но все же неприятно. Гуглил, но решения не.

"control may reach end of non-void function" Xcode
main.cpp:42:1: Control may reach end of non-void function Выдает такую ошибку, гуглил не помоглу.


Excel 2013 32-bit URLDownloadToFile пишет "Compile error: only comment may appear after End Sub End Function or End Prop
Добрый день! перепробовал все варианты и не вызывается функция URLDownloadToFile: пишет.

cpp:72:1: warning: control reaches end of non-void function [-Wreturn-type]

Ерунда. Предупреждение. Функция должна что-то возвращать. Поставь в строчку 71 return 0; Или
void delitel (int m, int n, int x, int i)

Добавлено через 2 минуты
На работу программы влияния оказывать не должно.
Хотя надо стремиться к "чистой" трансляции, без варнингов.

. delitel (m,n,x-1, i+1);
>
return 0;
>
Вот так? но тогда ответ k=0 всегда.
Вообще то функция действительно работает, но ответ дает не верный. Например при вводе 1 и 2 ответ 6422240. maytreya, все мои замечания касается только твоего
cpp:72:1: warning: control reaches end of non-void function [-Wreturn-type]

Спасибо за подсказку. Нашел еще одну логическую нестыковку, попробую добить до рабочего состояния)).

Добавлено через 3 часа 5 минут
Еще раз спасибо всем кто откликнулся. Второй вариант стал "рабочим". считает верно правда от варнинга не избавился. Конечно 1-й вариант гораздо изящней, но для тренировки 2-й то же не плох. )) Кому интересно вот код:

//считает верно, но постоянно выдает предупреждение. Не могу понять почему.
//вариант 2 Untitled-1.cpp:71:1: warning: control reaches end of non-void function [-Wreturn-type]
// 71 | >
// | ^ int delitel (int m, int n, int x, int i)
// n=x+i;
if (n>m)
swap (n,m);
if(x!=0)
if (m%x==0 && n%x==0)
return x;
return delitel (m,n,x-1, i+1);
>
return 0;
>

Кстати, не рискнул выделить в отдельную тему. Подскажите где можно узнать о правильном написании кода, а то мне тут давеча намекнули, что мол пишу коряво)))

Добавлено через 2 минуты

if (m%x==0 && n%x==0)
return x;
>
return delitel (m,n,x-1);
>
return 0;
> Твоя проблема не в том, что ты коряво пишешь, а в том, что не слушаешь, то что тебе говорят. Корявый код - это следствие.

Жирным пометил, на случай, если ты цвета не различаешь

Добавлено через 56 секунд

Добавлено через 2 минуты
вот когда убираю "return 0; " тогда считает правильно, но опять предупреждение

вот когда убираю "return 0; " тогда считает правильно, но опять предупреждение Ты лучше показывай как сделал, а то большие сомнения в твоих словах. Добавлено через 57 секунд
return 0; если на 13 строке, то ответ ноль

return 0 в конце добавь и всё будет правильно.

Добавлено через 23 секунды

При каких параметрах?

Добавлено через 1 минуту
Сделай return 1. Это когда общего делителя нет

ух ты. получилось. теперь бы понять почему. Спасибо огромное . буду разбираться)))

Добавлено через 4 минуты
еще раз спасибо. все понял

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Ошибка при компиляции - Expected '(' before 'void'
Добрый день. Я компилирую библиотечные функции под арм. На данной функции возникает ошибка.

Ошибка при компиляции Dev C++ 'typedef void* pthread_t'
Здравствуйте. Нужно установить программу D-ITG через Dev C++. Установил версию 5.10, открываю.


Error LNK2019: unresolved external symbol _glutSwapBuffers@0 referenced in function "void __cdecl Draw(void)"
Здраствуйте. У меня проблема такая, выдает ошибку ссылка на неразрешенный внешний символ, сам я в.

Предупреждение при компиляции
При компилирование выдается следующие предупреждения. Note: Some input files use unchecked or.

Предупреждение при компиляции.
День добрый. Изучаю Java совсем не давно по видео курсам. Вчера столкнулся с такой проблемой -.

"control may reach end of non-void function" Xcode


Error LNK2019: unresolved external symbol _glutSwapBuffers@0 referenced in function "void __cdecl Draw(void)"
Здраствуйте. У меня проблема такая, выдает ошибку ссылка на неразрешенный внешний символ, сам я в.


Excel 2013 32-bit URLDownloadToFile пишет "Compile error: only comment may appear after End Sub End Function or End Prop
Добрый день! перепробовал все варианты и не вызывается функция URLDownloadToFile: пишет.

какой будет результат оператора если условие в if будет ложным?

В данном случае, если уж решили проверять диапазон, то в случае выхода за границы можно кинуть исключение.

4 Answers 4

You are getting this error because if your for loop breaks due to breaking condition i < n; then it don't find any return statement after for loop (see the below, I mentioned in code as comment).

If for loop break due to i >= n then control comes to the position where I commented and there is no return statement present. Hence you are getting an error "reach end of non-void function in C".

Additionally, remove break after return statement. if return executes then break never get chance to execute and break loop.

Error: control may reach end of non-void function in C

I understand that the error means that the function may reach the end without returning anything, but I cannot figure out how that might happen.

149 1 1 gold badge 1 1 silver badge 3 3 bronze badges The complier does not analyze that "deeply" the "sense" of the code in a function. Just add return false; at the end of the function. This will even make the first if unnecessary.

9 Answers 9

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 .

55.4k 27 27 gold badges 141 141 silver badges 181 181 bronze badges (And the reason the compiler is scared is that a function typed to return an int must actually return an int , and not just fall off the end of the function) Another way to get rid of the warning is to add assert(false); at the end of the function, to clearly tell the compiler (and human reader) that you deliberately omitted the else case because you are sure it cannot happen.

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

78k 10 10 gold badges 141 141 silver badges 183 183 bronze badges The compiler is smart enough. The problem is that the user was not smart enough to specify a non-zero optimization level. -O0 is almost always a very very bad idea. Interesting idea, but I think not. For example, gcc gives this error with -O3 .

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.

198k 32 32 gold badges 340 340 silver badges 675 675 bronze badges I am skeptical of this. gcc 4.0.1 gives this warning with optimization cranked all the way up. Do you know of a specific compiler where optimization would make this message go away?

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.

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

This is the working code after little changes

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.


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;

Читайте также: