Jordan V Jordan V - 4 months ago 16
C Question

Unsure about what the 'control may reach end of non-void function' error message means

Trying to execute a search using a pseudo random generator to find whether value is in array. Every time I execute I get the following message:

helpers.c:46:1: error: control may reach end of non-void function [-Werror,-Wreturn-type]


What am I doing wrong?

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

}
else
return false;

}

Answer

Your logic appears to be wrong .Change

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

To

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

Otherwise, the loop will not execute more than one time.

The error message tells you that if if (n > 0) is true and the condition in for (int i = 0; i < n; i++) is false, then you don't return a bool (The compiler isn't intelligent enough to know that this won't happen)

Comments