Roman Lopez
Roman Lopez

Reputation: 65

Bool method returns wrong value

I created a bool contains(string) method for a linked list hash table which checks if a value is in the hash. I use a helper function to recurse, but when the helper function returns false, the bool contains(string) still returns true. I ran it through the debugger and I can clearly see that it returns false, and I'm not sure why.

Here is the current node being searched:

"laccoliths"->"morbiferous"->"oculi"->"unscabbarded"

the value I'm searching for is "typung".

Here's the code:

bool contains_h(string x, node * p) //helper method
{
    if (p == NULL)
        return false;
    else if (x == p->data)
        return true;
    else
        contains_h(x, p->next);
}

bool contains(string word) { return contains_h(word, head); }

Upvotes: 4

Views: 757

Answers (1)

Andrew Shepherd
Andrew Shepherd

Reputation: 45272

Nice simple one. You forgot to put 'return' on the final statement:

bool contains_h(string x, node * p) //helper method
{
    if (p == NULL)
        return false;
    else if (x == p->data)
        return true;
    else
        return contains_h(x, p->next);
}


And out of curiosity, I rewrote your code to a one-liner to see what it would look like:

bool contains_h(string x, node * p) //helper method
{
    return ((p!=NULL) && (x == p->data || contains_h(x, p->next)));
}

Personally, I would prefer to read your six lines. However, others might disagree, particularly because it would have avoided the missing return statement problem.

Upvotes: 7

Related Questions