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]?
return
statements are in conditional blocks. Thus the compiler sees this and gives you a warning. – PaulMcKenziereturn
, so the second example won't execute thereturn false;
at the end if it hit one of the otherreturn
s first. – Dmitriif (n < 1) {...}
part is actually unnecessary, since ifn
is less than1
thefor
loop wouldn't run (it's test would be false), and you'd skip over it to thereturn false;
at the end anyway. – Dmitri