4

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); 
Community
  • 1
  • 1
Nick
  • 823
  • 2
  • 10
  • 22

1 Answers1

7

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); 
Jts
  • 3,447
  • 1
  • 11
  • 14
  • the function works, but I don't think it is changing the value of `flag`. – Nick Mar 31 '16 at 04:49
  • @NickPredey it will work. If your function signature takes a reference, then it will get a reference to the argument you passed in. Here's a demo: http://ideone.com/tDKK0s – Jts Mar 31 '16 at 04:50
  • Okay, I will reevaluate my function and see if that is the problem. – Nick Mar 31 '16 at 04:52