Nick
Nick

Reputation: 898

How to pass a bool variable by reference in a non-bool function?

I looked at how to pass a bool by reference, but that function returned the bool inside of it. I also looked here on stack overflow, but the suggestions made by the commenters did not improve my situation. So,

I have a function:

myTreeNode* search_tree(myTreeNode *test_irater, char p_test, bool &flag)

That obviously returns a myTreeNode* type. I also have a variable, bool flag that I want to change the value of within the function. However, when I try to pass the bool by reference, I get an error message of

error: invalid initialization of non-const reference of type 'bool&' from an rvalue of type 'bool*'|

How do I go about passing a bool by reference without returning a bool? I am running on the latest version of CodeBlocks, if that is relevant.

Edit: code

myTreeNode* search_tree(myTreeNode *test_irater, char p_test, bool &flag)
{
    switch(p_test) 
    {
    case 'a':
        if (test_irater->childA == NULL)
            flag = false;
        else {
            test_irater = test_irater->childA;
            flag = true;
        }
        break;
    case 't':
        if (test_irater->childT == NULL)
            flag = false;
        else {
            test_irater = test_irater->childT;
            flag = true;
        }
        break;
    case 'c':
        if (test_irater->childC == NULL)
            flag = false;
        else {
            test_irater = test_irater->childC;
            flag = true;
        }
        break;
    case 'g':
        if (test_irater->childG == NULL)
            flag = false;
        else {
            test_irater = test_irater->childG;
            flag = true;
        }
        break;
    }
    return test_irater;
}

called like:

test_irater = search_tree(test_irater, p_test, &flag); 

Upvotes: 4

Views: 27112

Answers (1)

Jts
Jts

Reputation: 3527

You are using the addressof(&) operator, meaning &flag is converted to bool*

Remove it, and it should work:

test_irater = search_tree(test_irater, p_test, flag); 

Upvotes: 7

Related Questions