Elian ten Holder
Elian ten Holder

Reputation: 362

Strange bool returing behavior

I am trying to compare two strings character by character using the bool match(string,string) I created, I believe it compares correctly when I enter two strings that are not equal to each other it does output false! but when I check the bool it has not returned false. I can't think of a reason for this behavior and I hope somebody can help me. The code:

#include <iostream>
#include <cassert>
#include <cmath>
#include <fstream>
#include <vector>

using namespace std;

bool match(string pattern, string source)
{
    if(pattern.size() == 0&& source.size() == 0)
    {
        return true;
    }
    else if(pattern[0] == source[0])
    {
        pattern.erase(0,1);
        source.erase(0,1);
        match(pattern,source);
    }
    else
    {
        cout << "false" << endl;
        return false;
    }
}
int main()
{
    string test1 = "hballo";
    string test2 = "hallo";
    bool match_found =  match(test1,test2);
    if(match_found)
    {
        cout << "match found!"<< endl;
    } 
    else if(!match_found)
    {
        cout << "match not found!"<< endl;
    }
}

Upvotes: 0

Views: 123

Answers (4)

Dmytro
Dmytro

Reputation: 1390

Try this implementation:

bool match(const string& pattern, const string& source)
{
    int len = source.size();
    if (pattern.size() != len)
    {
        return false;
    }
    for (int i=0; i < len; ++i)
    {
        if (pattern[i] != source[i])
            return false;
    }
    return true;
}

Upvotes: 1

NPE
NPE

Reputation: 500327

You forgotten a return in

pattern.erase(0,1);
source.erase(0,1);
return match(pattern,source);
^^^^^^

Also, as pointed out by @melpomene, the pattern[0] == source[0] part is broken, since pattern or source (but not both) can be empty at this point.

Finally, needs to be said that the recursive approach is extremely inefficient here.

Upvotes: 1

malkassem
malkassem

Reputation: 1957

You are missing a return statement in you second else statment:

if(pattern.size() == 0&& source.size() == 0)
{
    return true;
}
else if(pattern[0] == source[0])  // no return statement.
{
    pattern.erase(0,1);
    source.erase(0,1);
    return match(pattern,source);
}
else
{
    cout << "false" << endl;
    return false;
}

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258598

You meant

return match(pattern,source);

otherwise you get undefined behavior.

Upvotes: 0

Related Questions