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

前端 未结 4 777
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 02:12

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 val         


        
4条回答
  •  没有蜡笔的小新
    2020-12-06 02:40

    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).

    for (int i = 0; i < n; i++){
        if (values[i] == value){
            return true;
            break;
        }
        else{ 
            return false;
        }
    }
      // here you should add either return true or false     
    }
    

    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'.

提交回复
热议问题