Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); }

like image 994
Roman Lopez Avatar asked Mar 14 '23 07:03

Roman Lopez


1 Answers

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.

like image 120
Andrew Shepherd Avatar answered Mar 28 '23 09:03

Andrew Shepherd