W. Zhu W. Zhu - 10 months ago 46
C Question

Passing return values over recursive functions in C

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);
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.

Answer Source

The behaviour of your program is undefined; you must explicitly return a value on all control paths.

A kind compiler will warn you of this; gcc certainly does if you set an appropriate warning level.

I believe that the fix in your case is to write return before your binsearch calls.

(The only exception to this is int main(...) where the compiler must introduce an implicit return 0; if it's missing).