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

匿名 (未验证) 提交于 2019-12-03 01:31:01

问题:

I cannot figure out why this error is happening: error: control may reach end of non-void function

Here is the code:

bool search(int value, int values[], int n) {      if (n 

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.

回答1:

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

for (int i = 0; i 

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.

   return true;  -- it returns from here.      break;  -- " remove it it can't executes after return "

Check your compiler should give you a warning - 'unreachable code'.



回答2:

That compiler warning is not correct. Anyway, there is a bigger problem with your code:

bool search(int value, int values[], int n) {      if (n 

This code only checks values[0] == value and then always returns. It's happening because of that else {return false;}.

You should write it this way:

bool search(int value, int values[], int n) {      if (n 

Now, function checks entire values array and then returns false if there was no matches. But if it found a match, it will instantly return true witout checking other elements.

Also, compiler will not emit a warning for this code.



回答3:

Your code is equivalent to

return (n > 0 && values [0] == value);

Either you are in the habit of writing very simple things in an excessively complicated way, or that code doesn't do what you want it to do.



回答4:

Some folks will probably hate this, but....

bool search(int value, int values[], int n) {     if (n 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!