0

How can I change this piece of code to a working one?!

#include <iostream>

void foo( bool &b )  // ERROR in passing argument 1 of ‘void foo(bool&)’
{
   std::cout << b << '\n';
}

int main()
{
  foo( false );   // ERROR invalid initialization of non-const reference of type ‘bool&’ from a temporary of type ‘bool’
  return 0;
}

Please note that I want to use call by reference method using &b.

mahmood
  • 23,197
  • 49
  • 147
  • 242

2 Answers2

2

call by reference requires an address, you're passing a constant. why no

bool aValue;
aValue = false;
foo(aValue);
keyser
  • 18,829
  • 16
  • 59
  • 101
michaelBurns
  • 77
  • 1
  • 10
1
foo( false );

this calls foo with a temporary object of type bool.

You cannot bind a temporary to non-const reference thus the error. It is possible in case of const reference

void foo( const bool &b );
//...
foo( false ); // OK

In your case it seems that you don't want to change an object being passed to the function but just to print it. Then there is no need to pass a reference, you can just pass object by value.

void foo( bool b ) { std::cout << b;}
//...
foo( false ); // OK
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • `Then there is no need to pass a reference, you can just pass object by value.` Only true with small objects. What if the object passed was a large datastructure? still better to have &. – cade Mar 22 '17 at 05:30