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.
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.
"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.
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.
Use return; instead of return(0); to exit a void function.
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With