0

I'm enrolled in a CS class and we are learning about recursion. The teacher showed us some code and I'm wondering why it works. buscar is a recursive search function in an array v[]. It returns the position of x in v[]

int buscar(int x, int v[], int n) {
    if(n == 0) return -1;
    if(x == v[n-1]) return n-1;
    buscar(x, v, n-1);
}

int main() {
    int v[] = {5, 3, 9, 12};
    printf("%d\n", buscar(5, v, 4));
}

The problem here is

buscar(x, v, n-1);

Shouldn't it return 'nothing' and terminate with some error? When I run this program, the result is correct as expected. Why does it work the same as

return buscar(x, v, n-1);
  • 4
    Don't try to wonder why undefined behavior works. – Federico klez Culloca Mar 26 '19 at 14:16
  • 4
    This is not how C works: you can generally never prove that a program is correct by running it. The only way to be sure that a program is correct is to prove that it follows the rules. – Kerrek SB Mar 26 '19 at 14:16
  • You are right. there should have been `return buscar(x, v, n-1);` instead. In C#, in example, this won't compile and the compiler says : *"not all code paths return a value"* – Cid Mar 26 '19 at 14:20

1 Answers1

0

As others commented, your code shows undefined behaviour.

The fact that you "accidentally" (or coidentially) get the results you expect probably is a result of the different levels of functions using the same processor register for returning function results.

glglgl
  • 89,107
  • 13
  • 149
  • 217