0

How do i assign a default value to a bool that is a reference?

I have a function like this :

void someFunction(bool a = true, bool& b)
{
 if(a)
   b = false;
 else
   std::cout << "nothings changed" << std::endl;
}

How should i assign the default value to b in this context?

void someFunction(bool a = true, bool& b = false)

will not work. So how should it be done?

7
  • stackoverflow.com/questions/1059630/… could be of some use. Feb 15, 2012 at 12:01
  • if b is supposed to be an out variable (i.e. you are returning some data with it) then you can not do it using references.
    – Naveen
    Feb 15, 2012 at 12:03
  • i dont understand. it works fine if i dont assign the default value. but life would be so much easier if i could. Feb 15, 2012 at 12:04
  • You don't need to give a default value to a reference-type argument, because the variable you call the function with already has a value when you make the call!
    – Mr Lister
    Feb 15, 2012 at 12:04
  • i dont want to use the variable all the time. i need to ignore it in some situations. that is why i need a default value for it, so that i can call the fun with one or no value at all.. Feb 15, 2012 at 12:08

3 Answers 3

5

You cannot initialize non-const references with values. You need a variable:

bool dummy_variable;

void someFunction(bool a = true, bool& b = dummy_variable)
{
    // ...
}

But it would probably make a lot more sense to simply return the bool:

bool someFunction(bool a = true)
{
    return !a;
}

Then the client can still decide for himself if he wants to ignore the result or not.

0

You cannot bound temporary object to a non-const reference. You need to use non-temp object:

bool bDefaultVal = false;

void someFunction(bool a = true, bool& b = bDefaultVal)
{
    ...
}
0

Why not use a pointer?

#include <iostream>

using namespace std;

void someFunction(bool a = true, bool* b = nullptr)
{
    if (b != nullptr) {
        *b = a; 
    }
}

int main()
{
   bool res = true;
   someFunction();
   cout << res << endl; // true
   someFunction(false);
   cout << res << endl; // true
   someFunction(false, &res);
   cout << res << endl; // false

   return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.