joe_young
joe_young

Reputation: 4125

C recursive function won't return true

I have a search function which employs recursion to perform a binary search of an array, values[], for a value:

int recurseSearch(int value, int values[], int min, int max) {

    if (value > values[max] || min > max) return 1;

    int midpoint = (max+min)/2;

    if (values[midpoint] > value)
        //search in left
        recurseSearch(value, values, min, midpoint);

    else if (values[midpoint] < value)
        //search in right
        recurseSearch(value, values, midpoint, max);

    else if (values[midpoint] == value)
        return 0;

    else 
        return 2;

    return 3;
}

The code that calls this simply calls recurseSearch(value, values, 0, n);
For the sake of verifying, I will set values[5] to equal {3, 11, 32, 54, 66}, value to be 3 (i.e. this should return 0), and n to therefore be 5.

So this gets called: recurseSearch(3, values, 0, 5);

Now I would expect this to eventually return, and print, 0, since 3 is indeed in the array. Upon debugging everything is going well up until the midpoint is 0, and therefore values[midpoint] == value is true, and so the return 0 line should run. However, what happens instead is that it does, but then comtrol aparently moves to the end (closing }) of the function, but then moves back up and runs the return 3; on line (here) 21.

I cannot understand why the return 0 statement doesn't just return out of the function and why the return 3 doesn't run at all


N.B. This problem is solved by removing the return 3; line, however this causes clang to complain, and the command for running (make) that I'm using, fatally have a hissy-fit, which I would much rather avoid

Upvotes: 0

Views: 658

Answers (1)

David Grayson
David Grayson

Reputation: 87516

I have not looked carefully at your code so there might be other bugs in it, but it sounds like you want the return value from the deepest recursive call to be passed up the stack all the way to the caller. In that case, you would remove the return 3; and simply return the value of each the recursive call you are making:

int recurseSearch(int value, int values[], int min, int max) {

    if (value > values[max] || min > max) return 1;

    int midpoint = (max+min)/2;

    if (values[midpoint] > value)
        //search in left
        return recurseSearch(value, values, min, midpoint);

    else if (values[midpoint] < value)
        //search in right
        return recurseSearch(value, values, midpoint, max);

    else if (values[midpoint] == value)
        return 0;

    else 
        return 2;
}

The way you originally wrote your code, the return values from the recursive calls were being ignored entirely, and the return 3; statement would be executed instead.

Upvotes: 1

Related Questions