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

前端 未结 4 770
没有蜡笔的小新
没有蜡笔的小新 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:28

    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 < 1) {
            return false;
        }   
    
        for (int i = 0; i < n; i++) {
            if (values[i] == value) {
                return true;
                break;
            }
            else {            // !
                return false; // ! <-- Here is the mistake.
            }                 // !
        }    
    }
    

    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 < 1) {
            return false;
        }   
    
        for (int i = 0; i < n; i++) {
            if (values[i] == value) {
                return true;
                // break;  <- BTW, it's redundant.
            }
        }    
        return false;
    }
    

    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.

提交回复
热议问题