I was writing a binary search function:
int binsearch(int seq[], int start, int end, int key)
{
int len = end - start + 1;
int mid = (start + end) / 2;
if (len <= 0)
return -1;
else if (key == seq[mid])
return mid;
else if (key < seq[mid])
binsearch(seq, start, mid - 1, key);
else
binsearch(seq, mid + 1, end, key);
}
I was not aware that I returned only once in the innermost call. I compiled it with gcc in my laptop, and it worked perfectly.
However, when I compiled that code in a cloud computer using clang, it threw me a warning that the control could reach the end of a non-void function. Then, I put another variable there to pass the return value over recursive calls.
Why did gcc compile it without any warning and yet the function gave the correct output? Is this a kind of compiler optimization? I thought C would not pass the return value automatically over recursive calls.
returnkeyword before the calls tobinsearchin the finalelse ifandelse.returnpreceding each call tobinsearch, you can get rid of all theelses.returnpoint in a function. Some people take coding standards like MISRA as a religion ...