8
votes

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

1
In scenario 1, all of your return statements are in conditional blocks. Thus the compiler sees this and gives you a warning.PaulMcKenzie
The two scenarios are doing different things. Scenario 1 the compiler is not smart enough to know that the for loop is not actually going to be used as when i=0 one or the other returns is going to be usedEd Heal
The function exits when it executes a return, so the second example won't execute the return false; at the end if it hit one of the other returns first.Dmitri
In the second example, the if (n < 1) {...} part is actually unnecessary, since if n is less than 1 the for loop wouldn't run (it's test would be false), and you'd skip over it to the return false; at the end anyway.Dmitri

1 Answers

6
votes

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:

  • When the loop executes at least once, there is a conditional return from both branches of the if statement, and
  • When the loop never executes, there is going to be a return from the conditional statement at the top of the function.

C standard does not require such checks, so the compiler issues a warning.