Reputation: 5
I have this snippet of code inside my project that has to search for an exact match inside an XML tree parsed with RapidXML. It does find the match but at the end it's always a null pointer match. I can't figure out the order in which I should code the function can somebody help me out?
xml_node<>* processNode(xml_node<>* node, char* lookout)
{
for (xml_node<>* child = node->first_node(); child; child = child->next_sibling())
{
cout << "processNode: child name is " << child->name() << " comparing it with " << lookout << endl;
if (strcmp(child->name(), lookout) == 0) {
return child;
}
processNode(child, lookout);
}
return nullptr;
}
Upvotes: -1
Views: 70
Reputation: 66459
You need to return the result of the recursion – recursive functions work exactly like non-recursive function and return to the place where they were called.
However, you can't return it directly, because then you would only ever look in one of the children.
You need to first store the value, and then return it only if you found what you were looking for.
Something like this:
for (xml_node<>* child = node->first_node(); child; child = child->next_sibling())
{
if (strcmp(child->name(), lookout) == 0) {
return child;
}
xml_node<>* result = processNode(child, lookout);
if (result != nullptr) {
return result;
}
}
Upvotes: 0
Reputation: 2271
You should have written
return processNode(child, lookout);
You should specify that you want to return the result of the recursive call.
When you write function call without return
statement, what it does is just creating local temporary object, which is returned by the function processNode
, and it immediately deletes it. Imagine you wanted to return the result of f
function from g
function, you would write.
Some_Type f()
{
if(.....)
{
....
}
return g();
}
Same is for recursive calling. You want to return the result of the next call. So you final function should be
xml_node<>* processNode(xml_node<>* node, char* lookout)
{
for (xml_node<>* child = node->first_node(); child; child = child->next_sibling())
{
cout << "processNode: child name is " << child->name() << " comparing it with " << lookout << endl;
if (strcmp(child->name(), lookout) == 0) {
return child;
}
return processNode(child, lookout); // Here is the sub.
}
return nullptr;
}
Upvotes: 2