When defining a function in C, I receive a 'control may reach end of non-void function' error in the compiler when writing the if/else logic a certain way (Scenario 1 below), but I do not receive the error when writing the logic another way (Scenario 2 below). To me, both ways of writing this function seem similar, so I am at a loss as to why version 1 won't compile.
Scenario 1
bool search(int value, int values[], int n)
{
int i;
if (n<1)
{
return false;
}
for(i=0;i<n;i++)
{
if (value==values[i])
{
return true;
}
else
{
return false;
}
}
}
Scenario 2
bool search(int value, int values[], int n)
{
int i;
if (n<1)
{
return false;
}
for(i=0;i<n;i++)
{
if (value==values[i])
{
return true;
}
}
return false;
}
Won't Scenario 2 always return false after the for loop? Or does the function essentially 'Stop' after returning a value for the first time, therefore returning 'true' once value matches values[i]?
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.
When we write the programs in C++. After executing programs, sometimes we get the error: 'warning: control reaches the end of non-void function', which means that certain functions that would have to return some values attain the termination. It might not give any value later.
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.
If control reaches the closing curly brace ( } ) of a non- void function without evaluating a return statement, using the return value of the function call is undefined behavior.
The problem is that C compiler is not smart enough to figure out that there is no scenario when the first function would reach the end without returning a value:
C standard does not require such checks, so the compiler issues a warning.
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