Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

controls

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 < 1) {
        return false;
    }   

    for (int i = 0; i < n; i++) {
        if (values[i] == value) {
            return true;
            break;
        }
        else { 
            return false;
        }
    }    
}

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.

like image 368
cspearsall Avatar asked Mar 14 '14 16:03

cspearsall


People also ask

What is the error control reaches end of non-void function?

If control reaches the end of a function and no return is encountered, GCC assumes a return with no return value. However, for this, the function requires a return value. At the end of the function, add a return statement that returns a suitable return value, even if control never reaches there.

What does control reaches end of non-void function mean in C?

"Control reaches end of non-void function" means your function has a path through it where the function ends without actually returning data of the type declared in the function declaration. In this case, your shift() function is declared to return an int.

What is non-void function in C?

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.

How do you exit from a void function in C?

Use return; instead of return(0); to exit a void function.


1 Answers

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

like image 192
Grijesh Chauhan Avatar answered Oct 18 '22 23:10

Grijesh Chauhan