Search code examples
cpointerstreebooleanpass-by-reference

pass bool variable by reference in function argument


I am trying to include a boolean flag in the below function argument to see whether a value already exists in the current tree structure of values.

VLTreeNode *addNewNode(AVLTreeNode *currentNode, int k, int v, bool *ifExist)
{
    if (currentNode == NULL)
    {
        return newAVLTreeNode(k, v);
    }
    if (k == currentNode->key && v == currentNode->value)
    {
        *ifExist = true;
        return currentNode;
    }
    else if ((k == currentNode->key && v < currentNode->value) || k < currentNode->key)
    {
        currentNode->left = addNewNode(currentNode->left, k, v, &ifExist);
        currentNode->left->parent = currentNode;
    }
    else if ((k == currentNode->key && v > currentNode->value) || k > currentNode->key)
    {
        currentNode->right = addNewNode(currentNode->right, k, v, &ifExist);
        currentNode->right->parent = currentNode;
    }
}

The call of this function would be like the following:

    bool ifExist = false;
    Tree->root = addNewNode(Tree->root, k, v, &ifExist);
    
    if (ifExist)
    {
        T->size++;
    }

and it does not work... could someone give me some hints what goes wrong in the code. Much appreciated.


Solution

  • In addNewNode, in your last two else if blocks, you're passing in &ifExist. But ifExist is a bool* already, should just pass in ifExist.

    I'm not sure, but It's possible that the return statements only in the first if blocks is ok so long as those cover all possible base cases of your recursive function. [I was not thinking straight, the return statements are definitely necessary in all branches - I meant that setting ifExist to true is only required in the base cases...]

    But yeah, the passing ifExist by reference (effectively now bool **) inside addNewNode is definitely not right.

    EDIT: To clarify, in your outermost call to addNewNode where you have...

    bool ifExist = false;
    Tree->root = addNewNode(Tree->root, k, v, &ifExist);
    

    ...you do need to pass in by reference. But inside addNewNode, your last two if else blocks should be

    else if ((k == currentNode->key && v < currentNode->value) || k < currentNode->key)
    {
        currentNode->left = addNewNode(currentNode->left, k, v, ifExist);
        currentNode->left->parent = currentNode;
    }
    else if ((k == currentNode->key && v > currentNode->value) || k > currentNode->key)
    {
        currentNode->right = addNewNode(currentNode->right, k, v, ifExist);
        currentNode->right->parent = currentNode;
    }
    

    I would advise doing instead:

    bool exists = false;
    bool * ifExist = &exists;
    Tree->root = addNewNode(Tree->root, k, v, ifExist);
    

    That way, the way addNewNode arguments look is consistent everywhere... which will prevent future arcidents due to copy paste.