dimanche 10 juillet 2016

C - Confused by 'control may reach end of non-void function' when using certain if/else syntax

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]?

Aucun commentaire:

Enregistrer un commentaire