#include <iostream>
using namespace std;

void someFunction(bool& a);

int main()
 bool a = true;

 if( a )
 cout <<"a = true";

 cout <<"a = false";

void someFunction(bool& a)
 a = false;

This will print out "a = false".

bool& a in the someFunction contains a memory address, no?
So how can you take a memory address = value?
Wouldn't that try to change the memory address into false in this case?

5 Years
Discussion Span
Last Post by pseudorandom21

Please re-read the section in your textbook about references. Yes, the bool& is a reference and yes, it has a pointer in it at the machine code level, but it is always automatically deferenced.


If you're still wondering, a variable on the stack has an address, which points to a reserved section of memory. The process is veery similar to using dynamically allocated objects with pointers.

Hopefully this small example can clear up some of it:

#include <iostream>
using namespace std;
int main()
	int someInt = 0; //<-- memory allocated and initialized to 0.
	cout << &someInt << endl;//<-- print the address of someInt
	//^^ It really prints the address of the base of the allocated section of memory.
	int *dynamicInt = new int(0);//<-- memory allocated (on the heap) and initalized to 0.
	cout << dynamicInt << endl;//<-- print the address of dynamicInt

	//Assign both sections of memory the value of 1.
	someInt = 1;
	*dynamicInt = 1;//<-- here the pointer is "de-referenced"
	cout << "someInt = " << someInt << endl;
	cout << "dynamicInt = " << *dynamicInt << endl;

	//Create a reference to both.
	int &someRef = someInt;//<-- disregard the syntax with regard to the address
	int &otherRef = *dynamicInt;//

	//Modify both with the reference.
	someRef = 2;
	otherRef = 2;
	cout << "someRef = " << someRef << endl;
	cout << "otherRef = " << otherRef << endl;

	delete dynamicInt;//<-- free dynamically allocated memory.

	cout << "Press RETURN to continue." << endl;
	return 0;

Edited by pseudorandom21: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.