Asmaa Asmae Asmaa Asmae - 1 month ago 14
C Question

error: control may reach end of non-void function

Please someone can explain me what's wrong why am I getting this error:

error: control may reach end of non-void function


I am trying to make a function
linearsearch()
taking a key and a table returning the index of an element if found.
It's confusing; I am a beginner and taking cs50 online course; I've never had this error before.

#include <stdio.h>
#include <string.h>
#include <cs50.h>

int linearsearch(int key, int array[]);

int main(int argc , string argv[])
{
int key = 0;
int table[]={2,4,5,1,3};

printf("%i is found in index %i\n",key,linearsearch(1,table));
}

int linearsearch(int key, int array[])
{
for(int i = 0;i<5;i++){
if(array[i] == key)
{
return i;
}
else{
return -1;
}
}
}

Answer

In the last for loop you're returning something from the function either way, so there shouldn't be any problem (except that your algorithm is wrong: it shouldn't return immediately if not found).

The problem is: the compiler doesn't necessarily see that you're returning whatever the data is. It just sees that don't end your routine by returning something.

Most compilers can figure out simple cases like:

   if (x) return 0; else return 1;
  // not returning anything in the main branch but ok as it's seen as unreachable
}

but in your case, you have a for loop wrapping the return instructions. Compilers are not control flow analysers. They do basic things, but certainly not formal execution. So sometimes they issue a warning where it's "OK" from your point of view.

Anyway, your algorithm is incorrect as mentioned earlier. Fix it by returning -1 only when the loop ends without finding anything.

In that case, you fix your bug AND the warning. So you see the warning was rightly detecting something fishy in your code.

Fixed code:

for (int i = 0; i < 5; i++)
{
    if (array[i] == key)
    {
         // found return & exit loop
         return i;
    }    
}
// not found, end of loop: return -1
return -1;