Rahul
Rahul

Reputation: 47

why this function is not returning value expected

below is a searchVal function for searching a value in a binary tree. nodes of binary tree are stored in a vector nodeVec with first object in vector as root.

structure of nodes

class bst{
public:
    //other functions..//
    int searchVal(int)
private:
    bst *lLink;
    int info;
    bst *rLink;

}

calling part in main

cout << "Enter Value to search ";
int val;
cin >> val;
int ret = nodeVec[0].searchVal(val);

if (ret == 2)
    cout << "Value Not Found" << endl << endl;
else
    cout << "Value Found" << endl << endl;

Function

int bst::searchVal(int val)
{
    if (info != val)
    {
        if (info > val)
        {
            if (lLink != NULL)
                lLink->searchVal(val);
            else
                return 2;
        }
        if (info < val)
        {
            if (rLink != NULL)
                rLink->searchVal(val);
           else
                return 2;
        }
    }

    if (info == val)
        return 1;
}

while debugging (using codeBlocks) i observed that after any condition is met for example if the condition info==val is met the execution pointer (arrow in the IDE pointing to line being processed) goes to end of searchVal and after that it go to nearest if(from the end) however it does not go into the block of that condition. It always returns the info stored in root node in ret not 1 or 2

Upvotes: 0

Views: 123

Answers (3)

Peter Bloomfield
Peter Bloomfield

Reputation: 5766

I think the major problem in your code is that you're not returning the result of the sub-tree searches; i.e. you should be doing this:

if(lLink!=NULL)
    return lLink->searchVal(val);

You're missing the return keyword. That means that some execution paths go all the way through to the end of the function, and never hit a return, which is potentially very bad. The compiler should be issuing an error or warning about that though.

Upvotes: 3

john
john

Reputation: 87959

Should be

  if(lLink!=NULL)
  return lLink->searchVal(val);
  ^^^^^^

Upvotes: 4

molbdnilo
molbdnilo

Reputation: 66371

The searchVal function needs a return value on every code path - everything else has undefined behaviour (which means that anything could happen).

Add a return to your calls to lLink->searchVal and rLink->searchVal.

(And if your compiler didn't warn you about this, you need to enable that warning.)

Upvotes: 3

Related Questions