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?

Prasanth Madhavan
  • 12,657
  • 15
  • 62
  • 94
  • http://stackoverflow.com/questions/1059630/default-value-to-a-parameter-while-passing-by-reference-in-c could be of some use. – another.anon.coward Feb 15 '12 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 '12 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. – Prasanth Madhavan Feb 15 '12 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 '12 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.. – Prasanth Madhavan Feb 15 '12 at 12:08
  • Then use a pointer in the function (with default value NULL) and pass the address of b – Mr Lister Feb 15 '12 at 12:09
  • What's the point of calling a function that changes a variable if you don't actually want to change a variable? Sounds like a strange design to me. – fredoverflow Feb 15 '12 at 12:10

3 Answers3

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.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
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;
}
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)
{
    ...
}
Bojan Komazec
  • 9,216
  • 2
  • 41
  • 51