Search code examples
returnvoid

void function not returning


I am having an issue returning out of a void function.

I can see the output printed when the name (input) is found, which returns true. The void function should return if the lambda (or name_checker) function returns true, but it still implementing remaining part of the function.


Solution

  • Change your function to return a bool, use that return value to quit immediately that you find something. Something like this

    bool findTreeNodeRecursively(unsigned indent, const TreeNode* node, const std::function<bool(const TreeNode*)>& name_checker){
    
        for (unsigned i = 0; i < indent; i++)
        {
            std::cout << "   ";
        }
        if (!node)
        {
            std::cout << "!nullptr!" << std::endl;
            return false;
        }
    
        indent++;
    
        if(name_checker(node) == true){
            return true;
        }
    
        if (auto control = dynamic_cast<const ControlNode*>(node))
        {
            for (const auto& child : control->children())
            {
                if (findTreeNodeRecursively(indent, child, name_checker))
                    return true;
            }
        }
        else if (auto decorator = dynamic_cast<const DecoratorNode*>(node))
        {
            if (findTreeNodeRecursively(indent, decorator->child(), name_checker))
                return true;
        }
        return false;
    }
    

    In a recursive function return only returns from one recursive call, it doesn't return all the way back to the top. If that's what you want you have to program it.