Jordan V - 1 year ago 67

C Question

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 Source

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)