Search code examples
crecursionreturnreturn-value

Why does this recursive function return the correct value?


Running a recursive function such as this one (compiled in gcc 7.3.1):

#include <stdio.h>

int arr[] = {5,1,2,6,7,3};
int arraySize = 6;

int recfind(int value, int index)
{
    if (arr[index] == value)
        return 1;
    if (index >= arraySize)
        return 0;
    // return recfind(value, ++index);
    recfind(value, ++index);
 }

int main() {
    printf("found 6? %d\n", recfind(6, 0));
    printf("found 9? %d\n", recfind(9, 0));
}

I get the following output:

found 6? 1
found 9? 0

Why does this work? Since the result of the recursive recfind call is not returned, how is the return value of higher-level calls chosen?


Solution

  • For C section is 6.9.1 from N1256:

    If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

    So the behaviour of your program is undefined.

    Why does this work?

    There is a possibility that the target + compiler you are using doesn't tamper the register containing the return value from last (recursive) function call. C doesn't mandate this mechanism for returning value in specs.

    So, though it may sound sensible, this is not guaranteed.