Elian ten Holder Elian ten Holder - 2 months ago 12
C++ Question

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

NPE NPE
Answer

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.