cozos
cozos

Reputation: 945

C++ returning boolean as 95

Problem with returning booleans in c++..

bool find( const TrieNode &node, const string word )
{

    if (word.length() == 0)
    {
         if (node.isWord)
         {
         cout << "TRUE" << endl;
         return true;
         }

         else
         {
         cout << "FALSE" << endl;
         return false;
         }
    }

    char firstletter = word.at(0);
    int index = firstletter - 'a';

    if (node.letters[index] == NULL)
    {
    return false;
    }

    else
    {
    find (*node.letters[index],word.substr(1,(word.length() - 1)));
    }

}

in my main I have

cout << find(*mynode,"word") << endl;

would yield to :

FALSE

95

clearly, a cout of FALSE means that the function returns false.. However, when I print out the result of the function, I get 95 which evaluates to true.. Any reason why it could be doing this?

thanks

Upvotes: 0

Views: 516

Answers (2)

aroth
aroth

Reputation: 54816

The problem is with your final if statement:

if (node.letters[index] == NULL) {
    return false;
}
else {
    //if execution gets here, the return value of the function is undefined
    find (*node.letters[index],word.substr(1,(word.length() - 1)));
}

...perhaps try:

if (node.letters[index] == NULL) {
    return false;
}
else {
    return find (*node.letters[index],word.substr(1,(word.length() - 1)));
}

Upvotes: 5

Necrolis
Necrolis

Reputation: 26171

Your missing a final return statement, so your getting whatever is in the low byte of EAX, which is random garbage. your probably want return true; at the very end of your function.

Your should pump the warning level of your compiler as it should be telling you this (something along the lines of "not all control paths return a value").

Upvotes: 6

Related Questions